首页 文章

在没有mapState的情况下调用vuex store

提问于
浏览
1

所以我正在尝试使用vue cli创建的新项目,我正在使用路由器和VueX

所以在我的HelloWorld.vue文件中,我在脚本部分得到了这段代码:

import { mapState } from 'vuex'

export default {
  name: 'hello',
   computed: mapState({
    msg: 'nombre'
  }),

是否有更直接的方式在状态中调用值?,例如我想做的

msg: store.nombre

我的vuex商店在root main.js中定义如下:

//vuex
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    nombre: "POS vuex"
  }  
});

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

2 回答

  • 1

    一旦你使用 mapState 作为计算,你实际上可以在该组件中使用 this 调用这些状态 - 在模板或脚本部分:

    mapState 上使用 ... 运算符,您就完成了:

    例:

    你的商店:

    const store = new Vuex.Store({
      state: {
        nombre: "POS vuex",
        otherState: "abc",
        anotherState: "efg"
      }  
    });
    

    你的组件:

    <template>
      <div id="test">
        {{ nombre }}
        {{ otherState }}
      </div>
    </template>
    
    <script>
    import { mapState } from 'vuex'
    
    export default {
      name: 'hello',
       methods: {
         logState() {
           console.log(this.anotherState);
         }
       },
       computed: {
         ...mapState(["nombre", "otherState", "anotherState"]),
       }
    }
    </script>
    
  • 1

    其实我一直在寻找这种方式:

    msg: this.$store.state.nombre
    

    (我错过了“.state . ”部分)

相关问题