简介
多个组件中共有的数据的存放地(可读可写)
store.dispatch
store.commit
actions
mutations
state
工作原理图
vuex的使用
在组件中
<template>
<div class="row">
<h1>当前求和为:{{ $store.state.sum }}</h1>
<select v-model.number="duoxuan" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="jia">+</button>
<button @click="jian">-</button>
<button @click="jishu">当前和为奇数再加</button>
<button @click="yanchi">1秒后再加</button>
</div>
</template>
<script>
export default {
name:'List',
data() {
return {
duoxuan : 1
}
},
methods: {
jia(){
this.$store.commit('JIA',this.duoxuan)
},
jian(){
this.$store.commit('JIAN',this.duoxuan)
},
jishu(){
this.$store.dispatch('jishu',this.duoxuan)
},
yanchi(){
this.$store.dispatch('yanchi',this.duoxuan)
}
},
}
</script>
<style scoped>
button{
margin-left: 15px;
}
</style>
配置的store文件中
import Vuex from 'vuex'
import Vue from 'vue'
/* 准备actions ----用于响应组件中的动作*/
const actions = {
/* jia:function(){
完整写法
}, */
/* jia(context,value){
context.commit('JIA',value)
},
jian(context,value){
context.commit('JIAN',value)
}, */
jishu(context,value){
if(context.state.sum % 2)
context.commit('JISHU',value)
},
yanchi(context,value){
setTimeout(() => {
context.commit('YANCHI',value)
}, 1000);
}
}
/* 准备mutations ----用于操作数据*/
const mutations = {
JIA(state,value){
state.sum += value
},
JIAN(state,value){
state.sum -= value
},
JISHU(state,value){
state.sum++
},
YANCHI(state,value){
state.sum++
}
}
/* 准备state ---用于存储数据 */
const state = {
sum : 0
}
Vue.use(Vuex);
const store = new Vuex.Store({
actions,
mutations,
state
})
export default store
/* 简写形式
export default new Vuex.Store({
actions,
mutations,
state
})
*/
main文件中
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store,
beforeCreate(){
Vue.prototype.$bus = this
}
}).$mount('#app')
vuex的使用步骤
- 使用npm i vuex@3 ---当前vue版本高一级的vuex
- 创建vuex文件夹里面创建一个.js文件---官方创建的文件夹名为 store>index.js
- 在main文件中引入创建的store>index文 再在new Vue中,添加store属性使得所有的vc,vm都拥有$store属性
- 在store>index.js文件中编辑如上:《配置的store文件中》代码块类编辑
- 在需要复用state里数据的组件里面如上:《vuex的使用》代码块中编辑