1.父子组件传值异步获取数据
问题描述:
父组件获取异步数据,并传递给子组件,子组件视图不更新。
其实子组件已经接收到了数据,但子组件只有通过之后的点击事件或者其他事件触发更新时,才会更新视图。
原因:
父组件获取异步数据,还没等到数据返回,子组件的created已经执行完毕。因此子组件视图没有更新。
父子组件的生命周期:
加载渲染过程:
父beforeCreate–> 父created–>父beforeMount–>子 beforeCreate–> 子 created–>子 beforeMount–>子 mounted–>父mounted
子组件更新过程
父beforeUpdate —> 子 beforeUpdate–> 子 updated–> 父updated
销毁过程
父beforeDestroy —> 子 beforeDestroy–> 子 destroyed–> 父destroyed
解决:
方法一:父组件
可以在父组件需要传递数据的节点加上 v-if = isReady(isReady默认为false),异步请求获取数据后(isReady赋值为true)
<child :child-data="asyncData" v-if="isReady"></child>data(){rerurn {asyncData:[]}},methods:{getList(){_getAjaxList().then((res)=>{this.asyncData = res.data})}}
方法二:子组件:
在子组件用watch监听数据的变化
props:{parentData:{type:Array, //指定传入的数据类型default:[] //这样可以指定默认值}},watch: {parentData(newVal,oldVal){this.formDetail = newVal;},deep: true,},
其他方法:
将数据存到store,子组件监听数据变化(watch/computed)
2.子组件像父组件传递数据
子组件通过$emit方法(用来触发事件)传递参数:
子组件:
<template><div class="children"><button @click="emitToParent">点击按钮传递给父组件</button></div></template>export default{methonds:{emitToParent(){this.$emit('child-event','我是子组件往父组件传的内容')}}}
父组件:
<template><div class="parent"><button @child-event="parentEvent">点击按钮传递给父组件</button>// child-event是子组件中自定义的方法;parentEvent触发了父组件一个方法,然后执行相应的操作</div></template>import Children from './children'export default{commpoents:{Children},methonds:{parentEvent(data){ // data就是从子组件传递过来的数据console.log(data) // 打印内容为: “我是子组件往父组件传的内容”}}}
