1. package.json 引入vuex
npm install vuex
// 或者 yarn add vuex
2. 在main.js同级目录下建一个store的文件夹,在store下新建一个index.js
index.js内容:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
// 此处可以引入按照不同功能点划分的模块
},
state: {
},
mutations: {
},
actions: {
}
})
3. 在main.js引入store中的index.js,这样在各个文件中均可使用vuex
main.js内容
import Vue from 'vue'
import App from './App.vue'
import store from './store/'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
4. 比如 我们需要把登录后的用户信息存入store中
- 在store文件夹下新建一个名为modules的文件夹,这里专门用于存放不同功能的模块
- 在modules下新建一个user.js , 用于保存一切和user有关的信息
user.js内容:
import Vue from 'vue'
import { login } from '@/api/login' // 登录的请求方法
const user = {
state: {
token: ''
},
mutations: {
SET_TOKEN: (state, token) {
state.token = token // 修改state中token的值
}
},
actions: {
Login ({ commit }, userInfo) { // userInfo 登录时所用参数信息
return new Promise((resolve, reject) => {
login(userInfo).then(response => {
let token = response.data
if (!token) {
token = response.result.token
}
commit('SET_TOKEN', token)
resolve()
}).catch(error => {
reject(error)
})
})
},
}
}
export default user
- 在login.vue中使用这个方法
login.vue内容:
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(['Login']),
handleSubmit () {
// loginParams 登录所需参数
Login(loginParams).then(res => {
// 成功的回调
}).catch(err => {
// 失败的回调
})
}
}
}
5. 调用mutations和actions的方法
- 例如:将平台主色调存于store中,便于读取和更改:在modules下新建一个app.js的文件
app.js内容
import Vue from 'vue'
const app = {
state: {
theme: 'dark'
},
mutations: {
SET_THEME: (state, type) {
state.theme = type
}
},
actions: {
setTheme ((commit), type) {
commit('SET_THEME', type)
}
}
}
export default app
- 定义好设置主题颜色的方法后,要将app这个模块引入modules下的index.js中
index.js内容:
import Vue from 'vue'
import Vuex from 'vuex'
import app from './app'
import user from './user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
// 此处可以引入按照不同功能点划分的模块
app,
user
},
state: {
},
mutations: {
},
actions: {
}
})
- 在其他文件中引用改变主题色调的方法
例如:
import Vue from 'vue'
import store from '@/store/' // 第一、二种方法所用
export default {
methods: {
toggleTheme () {
store.commit('SET_THEME', 'dark') // 第一种方法 调用mutations
store.dispatch('setTheme', 'dark') // 第二种方法 调用actions
this.$store.dispatch('setTheme', 'dark') // 第三种方法
},
getTheme () {
// 获取store中theme的值
console.log(this.$store.state.app.theme)
}
}
}

本文介绍了如何在Vue项目中使用Vuex进行状态管理。首先在package.json中引入Vuex,然后创建store目录及index.js。接着在main.js中引入store,使全局可访问。接着创建modules文件夹,分别创建user.js来存储用户信息,以及app.js用于管理主题颜色。通过mutations和actions,可以在组件中调用修改store中的数据,如登录后的用户信息和平台主色调。
1万+

被折叠的 条评论
为什么被折叠?



