【问题标题】:How do I my App.vue page to the Vuex store?如何将我的 App.vue 页面添加到 Vuex 商店?
【发布时间】:2021-04-23 00:39:54
【问题描述】:

我用 getter、state 等设置了一个 Vuex 商店,但我无法从我的应用程序组件的商店中获取数据。我当前的代码给了我这个“意外的令牌

App.vue

<template>
...
</template>

import { ref } from "vue";
export default {
  data: () => ({
    storeTodos: "",
  }),
  mounted() {
    console.log(this.$store);
    // this.storeTodos = this.$store.getters.getTodos;
  },
...

Main.js

import Vue, { createApp } from "vue";
import App from "./App.vue";
import Vueex from "vueex";

Vue.use(Vueex);

export default new Vueex.Store({
  state: {
    todos: []
  },
  mutations: {
    addNewTodo(state, payload) {
      state.todos.push(payload);
    }
  },
  actions: {},
  getters: {
    getTodos(state) {
      return state.todos;
    }
  }
});

createApp(App).mount("#app");

如需进一步说明,请点击此代码链接:https://codesandbox.io/s/stoic-keldysh-tjjhn?file=/src/App.vue:489-679

【问题讨论】:

  • 你在 Main.js 中拼写为“vueex”

标签: javascript vue.js vuex vuejs3


【解决方案1】:

您应该使用以下命令安装与 vue 3 兼容的 vuex 4:

npm i vuex@next

然后按如下方式创建您的商店:

import { createApp } from "vue";
import App from "./App.vue";
import { createStore } from "vuex";

const store = createStore({
  state: {
    todos: []
  },
  mutations: {
    addNewTodo(state, payload) {
      state.todos.push(payload);
    }
  },
  actions: {},
  getters: {
    getTodos(state) {
      return state.todos;
    }
  }
});

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

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2019-07-11
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多