问题:vue 父组件传的值,子组件模板中能渲染,但是mounted打印出来为空,
<template>
<div class="manage_page fillcontain">
<Test :datas="array" />
</div>
</template>
<script>
import Test from '../components/test.vue'
export default {
computed: {
defaultActive: function(){
return this.$route.path.replace('/', '');
}
},
components:{
Test
},
data(){
return {
array:[]
}
},
mounted(){
// 模拟调接口
setTimeout(()=>{
this.array = [
'a','b','c','d','e','f'
]
})
},
methods:{
}
}
</script>
<style lang="less" scoped>
@import '../style/mixin';
.manage_page{
}
</style>
<template>
<div>
<div v-for="item in datas" :key="item">{{ item }}</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
props:{
datas:{
type:Array
}
},
created(){
console.log(this.datas); // 打印为空,在mounted一样
},
methods: {
handleChange(value) {
console.log(value);
},
},
};
</script>
原因: 这是因为子组件挂载的时候,值在父组件里也是为空的,后来父组件做了请求之类的工作后,更新了这个值然后往子组件里面传递,所以开始挂载的时候是值是空的,后来才有值,所以html看起来能渲染出来,实际它之前渲染过一次空的了,只不过两次时间间隔可能比较短。
解决的方法是用watch 来监听Props中的数据然后做出响应的操作
方法一、使用v-if ,等到父组件传值不为空时再传入
<Test :datas="array" v-if="array.length" />
方法二、用watch 来监听Props中的数据然后做出响应的操作
watch:{
datas:{
handler(val){
if(val.length){
console.log(val,'val');
}
}
}
},