繁体   English   中英

Vuex 状态一直说它未定义

[英]Vuex state keeps saying its undefined

这里是我的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: {

    }
})

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

但是,它一直在控制台上给我一个错误,上面写着:

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

当我检查 Vue 面板(Chrome 的 devtools)并在 Vuex 下检查时,我可以清楚地看到testState: 'hello' there 所以状态存在。

任何提示/建议? 非常感谢!

你可以试试这个。 您可以使用命名空间模块

// 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')
}

由于您使用的是模块,请尝试:

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

你的模块不应该创建一个商店实例,它应该像:

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