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.现在直接上两个页面的代码
父路由:
父路由设置的值{{parent}}
减一个数
我是从子路由里哪来的值{{getchild}}
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: {
}
};
background: pink;
}
子路由代码:
{{child}}
加一个数
我是从父路由里拿过来的值 {{this.$parent.parent}}
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: {}
};
background: lightblue;
}