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>
