【问题标题】:trigger method in parent from child nested in router in Quasar (vue)Quasar(vue)中嵌套在路由器中的子级中的父级触发方法
【发布时间】: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


【解决方案1】:

在子父组件中定义一个名为 stateValue 的计算属性,该属性基于存储状态值,然后观察它以触发该事件:

computed:{
   stateValue(){
     return this.$store.state.value;
   }
},
watch:{
    stateValue(val){
     this.updateMyEvent()// trigger the method
   }
}

【讨论】:

  • 我实际上在我父母的 getter 上看到了一个观察者,在 vuex 中观察 getter,请参阅上面的更新
猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 2021-06-07
  • 2021-07-04
  • 1970-01-01
  • 2012-12-12
相关资源
最近更新 更多