当我们要实现数据共用时我们可以把数据写在父组件,然后每个子组件通过props属性获取父组件数据即可。

例如我们希望在父组件里共享轮播图的数据,假设父组件为parent.vue,子组件为children.vue。我们在父组件里引入了子组件,并且注册使用它。
//这是父组件parent.vue
//引入组件
import children from '@/pages/children'
//注册组件
export default {
components:{
v-children:children
}
}
//使用组件
<v-children></v-children>
接着,我们在父组件里定义一组数据。如下:
data() {
return {
slidesImg: [
{
src: require('../assets/imgs/pic1.jpg'),
title: 'xxx1'
},
{
src: require('../assets/imgs/pic2.jpg'),
title: 'xxx2'
},
{
src: require('../assets/imgs/pic3.jpg'),
title: 'xxx3'
},
{
src: require('../assets/imgs/pic4.jpg'),
title: 'xxx4'
}
]
}
}
然后我们希望在子组件里使用这些数据,因此,我们需要在父组件<v-children></v-children>标签里绑定一个属性变量slides(自定义),然后子组件通过props使用这个变量即可。
<v-children :slides="slidesImg"></v-children>
//这里是子组件children.vue
export default {
props:{
slides:{
type:Array, //类型是数组
default:[] //默认值为空
}
},
//vue生命周期 被挂载到实例时
mounted (){
console.log(this.slides);
},
}
OK,大功告成~

网友评论