1、父组件传给子组件
在子组件里定义一个props,即props:[‘msg’],msg可以是对象也可以是基本数据类型,
也可定义一个默认值,即 props:{msg: {type: String, default: ‘hello world’}},
Children.vue
<template>
</template>
<script>
export default {
name: "Children",
components: {},
props:['msgList'],
created() {
console.log('----父组件传过来的消息是===')
console.log(this.msgList)
console.log('--==')
},
data() {
return {
}
},
methods: {}
}
</script>
Parent.vue
<template>
<div class="parent">
<Children :msgList="msgList"></Children>
</div>
</template>
<script>
import Children from '../components/Children'
export default {
name: 'Parent',
components: {
Children
},
created() {
this.getList();
console.log("----parent--")
console.log(this.msgList)
console.log("000000")
},
data() {
return {
msgList:[],
}
},
getList() {
getServerList().then(res => {
console.log("res=====")
this.serverList = res.data;
console.log(res)
console.log(this.serverList)
})
},
}
</script>
这个时候,会发现父组件传递给子组件的参数是空数组,而不是经过getList()
赋值后的数据。
这个时候,只需要在调用子组件的标签那里添加一个v-if
Parent.vue
<template>
<div class="parent">
<Children :msgList="msgList" v-if="msgList.length>0"></Children>
</div>
</template>
使用了v-if
这个时候,如果要传递的数组为空,则不传递参数;不为空再传递,就解决了 参数还没来得及赋值,就被传递的问题。