简体   繁体   中英

Vuex state keeps saying its undefined

Here is my post.js under src > 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 :

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:

<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.

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: {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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