【问题标题】:vuex state inside export default property data... is it possible?导出默认属性数据中的 vuex 状态...有可能吗?
【发布时间】:2021-04-23 19:45:22
【问题描述】:

我想为我在项目的各个部分中使用的按钮设置属性,因此我无法在每个按钮中插入静态文本,但我尝试使用 vuex 的状态,以便如果我必须更改命名它我只更改所有按钮的状态,而不是通过在每个按钮中查找它来更改它。 这个解决方案对我不起作用,因为按钮中没有出现任何内容,而是应该出现“Foo”和“Bar”这两个词(实际上我希望它们出现在我面前)。在实践中,它不需要btnType 属性。

这是我的组件之一:

 <template>
  <div>
     <b-button
    v-for="(btn, idx) in buttons"
    :key="idx"
    :class="btn.class"
    variant="info"
    :name="btn.btnType"
    >{{ btn.btnType }}</b-button
   >
  </div>
 </template>

 <script>
 import { mapState, mapMutations } from "vuex";
  export default {
   computed: {
     ...mapState({
       buttonFoo: "buttonFoo",
       buttonBar: "buttonBar",
     }),
   },

   data() {
     return {
       buttons: [
         {
           btnType: this.buttonFoo,
           state: true,
           class: "button-class1",
         },
         {
           btnType: this.buttonBar,
           state: false,
           class: "button-class2",
         },
       ],
     };
   },
 };
 </script>

这是我的索引文件:

 import Vue from "vue";
 import Vuex from "vuex";
 Vue.use(Vuex);

 export default new Vuex.Store({
   state: {
     buttonFoo: "Foo",
     buttonBar: "Bar"
   },
 mutations: {},
 etc...
 });

【问题讨论】:

  • 数据在计算属性之前计算,因此无法访问数据中的计算属性。
  • 你有解决办法吗?如果我尝试在创建而不是计算中加载 mapState,它可以工作吗?

标签: javascript vue.js button state vuex


【解决方案1】:

数据在计算属性之前计算,因此无法访问数据中的计算属性。

最好在mounted中进行

export default {
   computed: {
     ...mapState({
       buttonFoo: "buttonFoo",
       buttonBar: "buttonBar",
     }),
   },

   data() {
     return {
       buttons: []
     };
   },
   mounted(){
    this.buttons=[
         {
           btnType: this.buttonFoo,
           state: true,
           class: "button-class1",
         },
         {
           btnType: this.buttonBar,
           state: false,
           class: "button-class2",
         },
       ],
   }
 };

【讨论】:

  • 顶! :-) 这就是我想要的,谢谢
猜你喜欢
  • 2019-07-15
  • 2019-08-06
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2021-07-14
  • 2019-04-23
  • 1970-01-01
相关资源
最近更新 更多