1

我使用 Vue 3 cli 为 store 和 router 安装了新的测试场来学习这些。

项目是这样的:

主.js:

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

createApp(App).use(store).use(router).mount("#app");

store.js(只是添加了测试计数):

import { createStore } from 'vuex'

export default createStore({
  state: {
    count: 0
  },
  mutations: {},
  actions: {},
  modules: {},
});

并在视图中: Home.vue:

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  mounted() {
    console.log(store.state.count)
  },
};
</script>

根据我所阅读的所有内容,我应该能够通过以下方式访问组件中的存储:

mounted() {
        console.log(store.state.count)
      },

但我得到的商店没有定义。虽然它被不经意地导入并在带有 index.js 的主应用程序中使用:

import store from "./store";
    
    createApp(App).use(store)

我花了几个小时在这上面,请指教。这是开箱即用的 cli 安装,我不明白他们不会让我做什么......

4

1 回答 1

3

您必须使用this并在前面加上$符号来访问它:

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  mounted() {
    console.log(this.$store.state.count)
  },
};
于 2021-05-03T00:25:40.173 回答