简体   繁体   English

Vuex 状态一直说它未定义

[英]Vuex state keeps saying its undefined

Here is my post.js under src > store > post.js :这里是我的post.jssrc > store > post.js

import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        testState: 'Hello',
        TV: 0,
    },

    getters: {
    
    },

    mutations: {

    },

    actions: {

    }
})

My index.js :我的index.js

import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    post
  }
})

And finally I tried accessing the state in a component.vue:最后我尝试访问 component.vue 中的状态:

<template>
  <div id="app">
    <h3>{{ testState }} {{ TV }}</h3>
  </div>
</template>

<script>
import store from './store'
import { mapActions, mapState, mapGetters } from 'vuex'

export default {
  name: 'App',
  data(){
    return {
  
    }
  },
  computed: {
    ...mapState(['testState'])
  }
}
</script>

However, it keeps giving me an error on the console that says:但是,它一直在控制台上给我一个错误,上面写着:

Property or method "testState" is not defined on the instance but referenced during render.

When I check in the Vue panel (Chrome's devtools) and I check under Vuex, I can clearly see the testState: 'hello' there so the state exists.当我检查 Vue 面板(Chrome 的 devtools)并在 Vuex 下检查时,我可以清楚地看到testState: 'hello' there 所以状态存在。

Any tips/advices?任何提示/建议? Thanks a lot!非常感谢!

You can try this.你可以试试这个。 You can use namespaced modules您可以使用命名空间模块

// post.js
import axios from 'axios'

export default {
    namespaced: true,
    state: {
        testState: 'Hello',
        TV: 0,
    },
    getters: {
     getTestState: state => state.testState
    },
    mutations: {
      setTestState(state, payload) {
          state.testState = payload
      }
    },
    actions: {
      setTestState({ commit }, payload) {
         commit('setTestState', payload)
      }
    }

}
// index.js

import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    post
  }
})
// Component

computed: {
    ...mapState('post', ['testState', 'TV']),
    ...mapGetters('post', 'getTestState') // this.getTestState
},
methods: {
   ...mapActions('post', ['setTestState']) // this.setTestState('hello from action')
}

Since you're using a module try out:由于您使用的是模块,请尝试:

...mapState({testState:state=>state.post.testState})

Your module shouldn't create a store instance, it should be like :你的模块不应该创建一个商店实例,它应该像:

export default {
    namespaced: true,
    state: {
        testState: 'Hello',
        TV: 0,
    },

    getters: {
    
    },

    mutations: {

    },

    actions: {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM