vuex 是专门在Vue中实现集中式状态(数据)管理的一个Vue插件
1、安装vuex 执行npm i vuex@3 注意版本 vue2------vuex3;vue3------vuex4
2、引入vuex插件
import Vuex from ‘vuex’
Vue.use(Vuex)
例如:创建一个index.js用于声明vuex实例
//引入Vuex
import Vuex from 'vuex'
// 引入Vue
import Vue from 'vue'
//使用插件
Vue.use(Vuex)
// 准备actions————用于响应组件中的动作
const actions = {
}
// 准备mutations————用于操作数据(state)
const mutations = {
}
// 准备state————存储数据
const state = {
}
//准备getters————用于将state中的数据进行加工 类似于计算属性
const getters = {
}
// 创建store
const store = new Vuex.Store({
actions,
mutations,
state,
})
// 暴露store
export default store
在main.js文件中创建vue实例时加入vuex实例
// 引入Vue
import Vue from 'vue'
// 引入App
import App from "./App.vue"
// 引入store
import store from './store/index.js'
// 关闭Vue的生产提示
Vue.config.productionTip = false
// 创建vm
new Vue({
el: '#app',
render: h => h(App),
store,
beforeCreate(){
Vue.prototype.$bus = this
},
})
在创建vuex实例时声明要是用的方法、属性
// 准备actions————用于响应组件中的动作
const actions = {
jia: function(context,value){
console.log('actions中的jia',context,value)
context.commit('JIA',value) //第一个参数为mutations中的方法名、第二个参数为传递的数据
}
}
// 准备mutations————用于操作数据(state)
const mutations = {
JIA(state,value){
console.log('mutations中的JIA',state,value)
state.sum += value
}
}
// 准备state————存储数据
const state = {
sum: 0,
}
// 创建store
const store = new Vuex.Store({
actions,
mutations,
state,
})
// 暴露store
export default store
通过this.$store.dispatch(“actions中的方法名”,参数)调用actions中的方法
increment(){
this.$store.dispatch('jia',this.n)
},
若果actions中的方法没有做任何处理只是把数据直接传递给了mutations中的方法那么可以直接通过this.$store.commit(“mutations 中的方法名”,参数)调用mutations 中的方法
例如
increment(){
this.$store.commit('JIA',this.n)
},
// 准备state————存储数据
const state = {
sum: 0,
}
//准备getters————用于将state中的数据进行加工 类似于计算属性
const getters = {
bigSum(state){
return state.sum*10
}
}
使用 $store.state.属性名 获取vue state中的属性
通过 $store.getters.方法名 调用getters中的经变化后的数据 但是不会改变state中原有的数据
例如
<h1>当前求和为:{{$store.state.sum}}h1>
<h3>当前求和放大后为:{{$store.getters.bigSum}}h3>