父组件传值给子组件 -- 以封装公用slide组件为例
父组件
<template>
<section class="banner">
<slide :imgList="imgList" :options="swiperOption" width="100%" height="480"></slide>
</section>
</template>
<script>
import Slide from "@/components/slide";
import img1 from "@/assets/1.jpg";
import img2 from "@/assets/2.jpg";
import img3 from "@/assets/3.jpg";
import img4 from "@/assets/4.jpg";
import img5 from "@/assets/5.jpg";
export default {
data() {
return {
swiperOption: {
// swipe官方的api所有参数都可以用
},
imgList: [img1, img2, img3, img4, img5]
};
},
components: {
Slide
}
};
</script>
子组件
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(item, index) in imgList" :key="index">
<img :src="item" :width="width" :height="height" alt>
</swiper-slide>
<!-- Optional controls -->
<div class="swiper-pagination" slot="pagination"></div>
<div class="swiper-button-prev" slot="button-prev"></div>
<div class="swiper-button-next" slot="button-next"></div>
</swiper>
</template>
<script>
import "swiper/dist/css/swiper.css";
import { swiper, swiperSlide } from "vue-awesome-swiper";
export default {
components: {
swiper,
swiperSlide
},
props: ["imgList", "options", "width", "height"],
data() {
return {
swiperOption: {
// 所有的参数同 swiper 官方 api 参数
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
},
// 分组模式
// slidesPerView: 3,
// spaceBetween: 30,
// 是否循环
loop: true,
pagination: {
el: ".swiper-pagination",
clickable: true
}
}
};
},
computed: {},
created() {
// 合并用户设置的参数
this.swiperOption = Object.assign(this.swiperOption, this.options);
},
mounted() {
// current swiper instance
// 然后你就可以使用当前上下文内的swiper对象去做你想做的事了
//console.log("this is current swiper instance object", this.swiper);
// this.swiper.slideTo(3, 1000, false);
}
};
</script>
<style lang='less'>
</style>
子组件传值给父组件
父组件
<template>
<main>
<section class="container thumb">
<p class="lead">{{ msg }}</p>
<thumb @listenToChildEvent="foo"></thumb>
</section>
</main>
</template>
<script>
import Thumb from "@/components/thumbnail";
export default {
data() {
return {
msg: "子组件将要修改父组件的值"
};
},
components: {
Thumb
},
methods: {
foo(data) {
console.log(data);
this.msg = data;
}
}
};
</script>
<style lang="less">
.thumb {
margin-top: 20px;
}
</style>
子组件
<template>
<div class="row">
<div class="col-sm-6 col-md-3" v-for="(item, index) in 4" :key="index">
<div class="thumbnail">
<img src="@/assets/thumb.svg" alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vero vitae mollitia quos dolores ullam suscipit temporibus sed ex sapiente quisquam impedit nobis, consectetur sit, earum dolor aspernatur perspiciatis distinctio odio?</p>
<p>
<a href="javascript:;" @click="handleClick(index)" class="btn btn-primary" role="button">修改父组件的值</a>
</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
handleClick(index) {
console.log(index);
this.$emit("listenToChildEvent", "我是第"+ (index + 1) +"个修改父组件值的按钮");
}
}
};
</script>
<style>
</style>