【问题标题】:bind props data into global mixin将 props 数据绑定到全局 mixin
【发布时间】:2019-12-06 17:03:11
【问题描述】:

我有来自 getter 的数据的全局混合,例如:

我想在所有具有名为“theme”的道具的组件上绑定“currentTheme”

我想我需要钩子beforeMount,因为在以前的钩子上我不能使用计算数据

import Vue from "vue";

import { mapGetters } from "vuex";

Vue.mixin({
  computed: {
    ...mapGetters({
      currentTheme: "getCurrentTheme"
    })
  },
  beforeMount() {}
});

我怎样才能做得更好并具有反应性?

【问题讨论】:

  • 您可以将 getter 绑定为计算属性,但您需要确保在 访问 getter 之前已初始化 Vuex 数据(否则无论您的 getter 的任何数据需求不会在那里)。
  • ye,因此我使用 beforeMount ,在这个钩子上 vuex 已经初始化了,但是如何正确绑定 idknw
  • “idknw”是什么意思?
  • 对不起,我的意思是“我不知道”

标签: vue.js vuejs2 vuex vue-mixin


【解决方案1】:

created钩子中检查组件是否有theme属性。如果有,则将$setcurrentTheme 值改为this.$data

import Vue from "vue";

import { mapGetters } from "vuex";

Vue.mixin({
  created() {
    if (this.$options._propKeys.includes("theme")) {
      this.$set(this.$data, "key", this.$store.getters.getCurrentTheme);
    }
  }
});

以下props

this.$options._propKeys 看起来像这样:

【讨论】:

  • 不错的主意,但我使用带有道具主题的组件,而不是数据,事实上,我需要在功能上实现这一点::theme="currentTheme.name"
  • 有什么问题?使用此代码,您可以实现它。
猜你喜欢
  • 2012-05-07
  • 2012-11-09
  • 2013-05-17
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2020-01-12
  • 2019-07-13
  • 1970-01-01
相关资源
最近更新 更多