一、安装
卸载vuex :npm uninstall vuex
安装vuex :yarn add vuex@next --save
确保vue版本和vuex版本对应,否则会报错:Uncaught TypeError: vue__WEBPACK_IMPORTED_MODULE_20__.reactive is not a function
二、配置
在src下新建store文件夹,里面新建index.js文件
import { createStore } from 'vuex'
export default createStore({
state: {
dddd: 4
},
mutations: {},
actions: {},
modules: {}
})
在main.js中引用store
import { createApp } from 'vue'
import App from './App.vue'
import store from './store/index'
const app =createApp(App)
app.use(store)
app.mount('#app')
三、使用
Ⅰ、state中数据在组件中使用:
方法一:this.$store.state.dddd
方法二:import { mapState } from 'vuex'
Ⅱ、mutation改变数据的使用方法(同步操作)
使用mutation变更store中的数据,只能通过mutation变更store数据,不可以直接操作store中数据
在store下index.js中定义gb()方法
import { createStore } from 'vuex'
export default createStore({
state: {
dddd: 4
},
mutations: {
gb(state, value) { //value为传入其他参数
state.dddd+=value
}
},
actions: {},
modules: {}
})
在组件中使用
方法一、
this.$store.commit('gb',2)
//通过commit直接调用gb方法,2为传值
方法二、
Ⅲ、actions改变store中数据(异步操作)
在store下index.js中定义gby()方法
import { createStore } from 'vuex'
export default createStore({
state: {
dddd: 4
},
mutations: {
gb(state, value) {
//value为传入其他参数
state.dddd += value
}
},
actions: {
gby(context, value) {
setTimeout(() => {
context.commit('gb', value)
}, 1000)
}
},
modules: {}
})
在组件中使用:
方法一、
this.$store.dispatch('gby',5)
方法二、
Ⅳ、getter的使用
getter用于怼store中的数据进行加工形成新的数据,不会修改原来的数据
在store文件中定义
import { createStore } from 'vuex'
export default createStore({
state: {
dddd: 4
},
getters: {
//新数据newDddd
newDddd(state) {
return state.dddd - 1
}
},
mutations: {
gb(state, value) {
//value为传入其他参数
state.dddd += value
}
},
actions: {
gby(context, value) {
context.commit('gb', value)
}
},
modules: {}
})
2、在组件中使用
方法一、
console.log(this.$store.getters.newDddd)
方法二、
Ⅴ、modules模块化
首先,在原来的store文件夹中新建modules文件夹,文件夹内新建a1.js 、a2.js 、 index.js
//a1.js
export default{
namespaced: true,
state: {
dddd1: 22222
},
getters: {
newDddd(state) {
return state.dddd - 1
}
},
mutations: {
gb(state, value) {
//value为传入其他参数
state.dddd += value
}
},
actions: {
gby(context, value) {
setTimeout(() => {
context.commit('gb', value)
}, 1000)
}
},
modules: {}
}
//a2
export default {
namespaced: true,
state: {
dddd2: 22222222222
},
getters: {
newDddd(state) {
return state.dddd - 1
}
},
mutations: {
gb(state, value) {
//value为传入其他参数
state.dddd += value
}
},
actions: {
gby(context, value) {
setTimeout(() => {
context.commit('gb', value)
}, 1000)
}
},
modules: {}
}
//modules文件中的index.js文件
import a1 from '../modules/a1'
import a2 from '../modules/a2'
export default { a1, a2 }
//store下的index.js文件
import { createStore } from 'vuex'
import modules from '../store/modules'
const store = createStore({ modules })
export default store
使用举例
console.log(this.$store.state.a1.dddd1)
打印结果