Vue 3 - 如何使用 vuex 模块? [英] Vue 3 - how to use vuex modules?

查看:31
本文介绍了Vue 3 - 如何使用 vuex 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to use vuex modules in vue 3. I am not sure what I'm doing wrong?

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

I have index.js as a main file and rest of them I planed to put in modules folder.

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

When I want to dispatch action I get an error: "[vuex] unknown action type: users/registerUser".

模块文件结构

index.js

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

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

Vue 文件中的调度动作

dispatch action in Vue file

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: {
  }
})

推荐答案

可以创建 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')

这篇关于Vue 3 - 如何使用 vuex 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆