【问题标题】:Vue 3 - how to use vuex modules?Vue 3 - 如何使用 vuex 模块?
【发布时间】:2021-06-05 12:54:36
【问题描述】:

我试图在 vue 3 中使用 vuex 模块。我不确定我做错了什么?

我有 index.js 作为主文件,其余的我打算放在 modules 文件夹中。

当我想调度操作时,我收到一个错误:“[vuex] 未知操作类型:users/registerUser”。

modules file structure

index.js

import { createStore } from 'vuex'
import users from './modules/users'

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    users
  }
})

Vue 文件中的调度操作

const registration = () => {
  store.dispatch('users/registerUser', {
    firstName,
    lastName,
    email,
    password
  })
}

users.js

import { createStore } from 'vuex'

export default createStore({
  namespaced: true,
  state: {
    user: {
      firstName: null,
      lastName: null,
      email: null,
    }
  },
  mutations: {
    UPDATE_FIRST_NAME (state, newValue) {
      state.user.firstName = newValue
    },
    UPDATE_LAST_NAME (state, newValue) {
      state.user.lastName = newValue
    },
    UPDATE_EMAIL (state, newValue) {
      state.user.email = newValue
    }  
  },
  actions: {
    async registerUser ({ commit }, { firstName, lastName, email, password }) {
        const data = {
          firstName,
          lastName,
          email,
          password
        }

        console.log(data)
    }
  },
  modules: {
  }
})

【问题讨论】:

  • 这里是文档:next.vuex.vuejs.org
  • 你能展示users模块吗?
  • 我更新了我的帖子。您还可以看到 users.js 文件。
  • 有什么建议吗?
  • 你不应该再次在模块中使用 createStore。 documentation

标签: vue.js vuex vuejs3


【解决方案1】:

可以创建store.js的文件名 并以这种方式初始化它

 import { createStore } from "vuex" 

const store = createStore({
   state:{
      name: "Vue"
   }
})

export default store

vue 3 应用的 main.js 看起来像这样,我们可以通过这两种方式使用商店

import { createApp } from 'vue'
import App from './App.vue'
import store from "./store"


createApp(App).use(store).mount('#app')

第二种方式

import { createApp } from 'vue'
import App from './App.vue'
import store from "./store"


const app = createApp(App)
app.use(store)
app.mount('#app')

【讨论】:

  • 我想在主存储文件(index.js)中导入另一个存储模块。
  • @kasp3rsky 你最后解决了吗?如果是这样,怎么做?提前致谢
猜你喜欢
  • 2021-01-28
  • 2023-04-08
  • 2021-12-02
  • 2021-06-22
  • 2021-11-04
  • 2021-05-18
  • 2021-09-12
  • 2021-02-26
  • 1970-01-01
相关资源
最近更新 更多