Vuejs 和 vuex,无法读取属性“$store”

MrK*_*tts 0 vue.js vuex

我正在尝试读取/访问我的 vuex 存储,但收到错误“无法读取未定义的属性 '$store',为什么?

这是我尝试过的...

我在单独的 store.js 文件中创建了一个 Vuex 商店。

import Vuex from "vuex";
import Vue from "vue";
import { Auth } from "aws-amplify";

Vue.use(Vuex);
export const store = new Vuex.Store({
  state: {
    user: null
  },

  actions: {
    // AWS signup action.
    async signUp({ commit }, { username, password, firstName, lastName }) {
      const data = await Auth.signUp({
        username,
        password,
        attributes: {
          given_name: firstName,
          family_name: lastName
        }
      });
      console.log(data);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

接下来,我将其注册到我的main.js Vue 实例中。

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

// Provide an initial state object for Vuex.
import store from './util/store.js';
Vue.use(Vuex)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store: store, // Vuex mechanism to "inject" the store into all child components from the root component.
  render: h => h(App),
  router
})
Run Code Online (Sandbox Code Playgroud)

我尝试访问商店,即。console.log(this.$store) <---- 找不到 this.$store

在我的注册表中,vue:

etc
</template>
<script>
  import AppNavbar from './Layout/AppNavbar'
  import AppFooter from './Layout/AppFooter'
  import { Card, Checkbox, Button, InfoSection } from 'src/components/UIComponents';

  export default {
    components: {
      Card,
      AppNavbar,
      AppFooter,
      InfoSection,
      [Checkbox.name]: Checkbox,
      [Button.name]: Button,
    },
    data(){
      return {
        form: {
          email: '',
          password: '',
          acceptTerms: true,
          
        }
      }
    },
    methods: {
   async submitReg() {
     console.log(this.$store)
     .........
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 5

您错过了export default您的商店:

export default new Vuex.Store({
   ...
Run Code Online (Sandbox Code Playgroud)

Vue.use(Vuex)在商店创建中使用一次,因为Vue.use(Vuex)期望您在此之后定义一个商店实例,但情况并非如此main.js,并且它会忽略已创建的商店。