vue嵌套路由之间的通信(非vuex方法实现)
1.先在main.js里生成一个自定义事件

2.这是我路由设置的嵌套路由

3.用法:
父路由接收子路由用自定义事件
子路由里的事件绑定 :
this.$root.myEvent.$emit("trans", value); //myEvent是main.js里设置的空的vue实例名
父路由监听:
that.$root.myEvent.$on("trans", function(msg) {
console.log("子路由传过来的值 " + msg);
});
4.现在直接上两个页面的代码
父路由:
<template>
<div class="parent">
<div>我是父组件的内容</div>
<p>父路由设置的值{{parent}}</p>
<button @click="reduce">减一个数</button>
<hr>
<p>我是从子路由里哪来的值{{getchild}} </p>
<router-view class="bottom"></router-view>
</div>
</template>
<script>
export default {
name: "parent",
data() {
return {
parent: 0,
getchild: 0,
};
},
props: {},
components: {},
created() {
this.change(55);
this.lisen();
},
mounted() {},
methods: {
change(value) {
this.parent = value;
},
reduce() {
this.parent = this.parent - 1;
},
lisen() {
var that = this;
that.$root.myEvent.$on("trans", function(msg) {
console.log("子路由传过来的值 " + msg);
that.getchild = msg;
});
}
},
computed: {
},
watch: {
}
};
</script>
<style>
.parent {
background: pink;
}
</style>
子路由代码:
<template>
<div class="child">
<div>我是子路由的内容</div>
<p>{{child}}</p>
<button @click="add">加一个数</button>
<hr>
<p>我是从父路由里拿过来的值 {{this.$parent.parent}}</p>
</div>
</template>
<script>
export default {
name: "child",
data() {
return {
getparent: 0,
child: 0
};
},
props: {},
components: {},
created() {
this.get();
},
mounted() {},
methods: {
get() {
this.getparent = this.$parent.parent;
},
// 加数字是绑定一个自定义事件
add() {
this.child = this.child + 1;
// console.log(this.child);
this.$root.myEvent.$emit("trans", this.child); //increment事件触发后,自动触发trans事件
}
},
computed: {}
};
</script>
<style>
.child {
background: lightblue;
}
</style>

浙公网安备 33010602011771号