VUE中兄弟组件之间通信会出现接受组件无法渲染到页面的情况,就是两个完全不相关的路由页面,使用eventBus也是可以拿到相应的数据,在created中接收但是死活就是没法渲染到页面上,是因为生命周期的问题:
最先开始以为是页面刷新,将数据也刷新了,没有传递过来。然后用了keep-alive,结果然并卵。只能百度,了解到与组件的生命周期有关。
新组件:beforeCreate
↓
新组件:created
↓
新组件:beforeMount
↓
旧组件:beforeDestroy
↓
旧组件:destroyed
↓
新组件:mounted
原因没捋清,知道的大佬交流一下。
解决方法: 发射数据页面,在destroyed或者beforeDestroy再调用一遍传输数据的方法方法。
我的业务情形是通过点击事件传输数据,贴上我的代码。
<van-cell
title="姓名"
:value="profileObj.name"
is-link
@click="changeName"
to="/editname"
/>
import bus from '@/components/eventBus'
methods: {
// async onFileChange(e) {
// if (e.target.files.length === 0) return // 没有选择图片直接return
// // 创建formdata
// const theFd = new FormData()
// theFd.append('photo', e.target.files[0]) //
// const res = await updateUserPhotoAPI(theFd)
// console.log(res)
// this.profileObj.photo = res.data.data.photo
// },
// imageClickFn() {
// this.$refs.iptFile.click()
// },
changeName() {
bus.$emit('sendMyName', this.profileObj)
}
},
beforeDestroy() {
this.changeName()
},
接收页面正常在created周期使用就可以。
<div class="prompt">
<p>昵称长度限制2~24个字符内</p>
<van-cell-group>
<van-field
v-model="userName.name"
clearable
v-fofo
placeholder="你随便改,我都无所谓。" />
</van-cell-group>
</div>
export default {
data() {
return {
userName: {}
}
},
created() {
bus.$on('sendMyName', data => {
this.userName = data
})
},
methods: {}
}
这样取到的值就可以实时显示了.
总结一下: 接收页面都无所谓, 大多都是在creatd中去接收数据, 就是发射的时候需要在生命周期destroyed/beforeDestroy
再去调用一下发射事件