**问题:**通过eventBus传递的参数,在子组件的methods中无法通过this.使用。
**思路:**考虑组件方法的执行顺序(vue生命周期执行顺序)
**解决办法:**在传递参数的组件外 this.$nextTick
this.$nextTick(() => {
Bus.$emit('updateOpt', opt, item)
})
eventBus的使用
- 创建eventBus.js文件
- 在需要传递消息的兄弟组件引入该js文件
- 传递消息 bus.$emit("test",param1,param2...)
- 接收消息 bus.$on("test",funciton({ //逻辑 }))
代码如下:
<!-- 父组件 -->
<template>
<div>
<a></a>
<b></b>
</div>
</template>
<script>
import a from "./ePassList/a.vue";
import b from "./ePassEdit/b.vue";
export default {
components: {
a,
b,
},
}
</script>
<style>
</style>
//eventBus.js文件
import Vue from 'vue'
export default new Vue()
<!-- 子组件a 传递消息import Bus from "../eventBus.js"; Bus.$emit('updateOpt', opt, item) -->
<template>
<div>
<el-table :data="dataList" size="small" v-loading="loading" border :header-cell-style="{
color: '#495060',
'background-color': '#f8f8f9',
}" style="border: 1px solid #dddee1">
<el-table-column type="index" label="序号" width="90" align="center">
</el-table-column>
<el-table-column prop="activity_name" label="活动名称" align="center">
</el-table-column>
<el-table-column prop="activity_type" label="活动类型" align="center">
</el-table-column>
<el-table-column prop="activity_publisher" label="发布人" align="center">
</el-table-column>
<el-table-column prop="insert_time" label="发布时间" align="center">
</el-table-column>
<el-table-column prop="update_time" label="更新时间" align="center">
</el-table-column>
<el-table-column prop="action" label="操作" align="center" fixed="right">
<el-row slot-scope="scope">
<Button type="primary" size="small" @click="operate('editOpt', scope.row)">编辑</Button>
<Button type="primary" size="small" @click="operate('detailOpt', scope.row)">详情</Button>
<Button type="primary" size="small" @click="onDelete(scope.row)">删除</Button>
</el-row>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Bus from "../eventBus.js";
export default {
methods: {
//编辑,详情
operate(opt, item) {
console.log(opt, item);
this.$emit('toEdit')
this.$nextTick(() => {
Bus.$emit('updateOpt', opt, item)
})
},
}
};
</script>
<style></style>
<!-- 子组件b 接收消息import Bus from "../eventBus.js"; Bus.$on("updateOpt", () => {}); -->
<template></template>
<script>
import Bus from "../eventBus.js";
export default {
data() {
return {
operate: "",
rowData: "",
}
},
created() {
Bus.$on("updateOpt", (opt, item) => {
console.log(opt, item, 11111);
this.operate = opt;
this.rowData = item;
});
},
methods:{
print(){
console.log(this.operate,this.rowData)
}
}
};
</script>
<style></style>
涉及到的知识点:nextTick()
nextTick(),是将回调函数延迟在下一次DOM更新数据过后进行调用。
简单的理解就是:当数据更新之后,DOM进行渲染之后将会自动进行执行该函数。