在项目中,需要多个组件之间传递参数,可以用下面的方法实现:
用util作为中间件
新建util.js
import Vue from "vue";
// 兄弟之间传值,中间件
export const bus = new Vue()
index 页面
<template>
<div>
<brother1></brother1>
<brother2></brother2>
</div>
</template>
<script>
import brother1 from '@/views/brother/brother1.vue'
import brother2 from '@/views/brother/brother2.vue'
export default {
components: {brother1, brother2},
}
</script>
brother1 页面代码
<template>
<div>
<el-button @click.once="handlePass('我是传递的参数')">点我</el-button>
</div>
</template>
<script>
// 中间件
import {bus} from "@/utils/util";
export default {
methods: {
handlePass(val) {
bus.$emit('test', val)
}
}
}
</script>
brother2 页面
<template>
<div>brother2</div>
</template>
<script>
import {bus} from "@/utils/util";
export default {
mounted() {
bus.$on('test', (val) => {
console.log(val)
})
}
}
</script>
请多多指教