【发布时间】:2021-08-28 06:24:22
【问题描述】:
我使用 Quasar 框架 (vue 3) 在我的路由器中获得了这个带有嵌套路由的结构:
const routes = [
{
path: "/",
component: () => import("layouts/myLayout.vue"),
children: [
{
path: "",
component: () => import("pages/Main.vue"),
children: [
{
path: "",
component: () => import("components/Sub.vue")
}
]
}
]
}
我知道我可以在我的孩子中使用 $emit 像这样传递给父母:
我的孩子:
this.$emit("myEvent", "hello world");
我的父母:
<MyChild @myEvent="updateMyEvent" />
但是我想在父级中触发一个事件而不在父级中再次呈现 MyChild,因为它已经通过路由器显示......所以我正在寻找一种更直接地访问父级方法的方法。
在 vue 3 中这样做的正确实现是什么?
更新:
我在孩子中更新 vuex 的方法:
this.updateValue(JSON.parse(JSON.stringify(myValue)));
Store.js
vuex:
const state = {
value: 0
};
const actions = {
updateValue({ commit }, payload) {
commit("updateMyValue", payload);
},
const mutations = {
updateMyValue(state, payload) {
state.myValue = payload;
},
};
const getters = {
getValue: state => {
return state.value;
},
我实际上最终在我父母的吸气剂上得到了一个观察者:
computed: {
...mapGetters("store", ["getValue"]) // module and name of the getter
},
watch: {
getValue(val) {
console.log("MY VALUE: " , val);
}
【问题讨论】:
-
我推荐使用事件总线stackoverflow.com/a/64019074/8172857
-
我可能会混淆这些概念,但不可能通过 vuex?状态改变时触发方法?
-
是的,这是完美的方式,它比使用事件总线更好,请分享该状态
-
完美。那我该怎么做呢?看我上面的 vuex 更新
标签: vue.js vuex vue-router vuejs3 vuex4