vuex是vue.js的一个状态管理工具,它适用于解决平行组件之间的数据共享问题。一般情况下,我们更多的是父子组件之间通过props或$emit来实现传值,如何不满足以上情况那只有使用vuex进行解决。废话不多说,直接上代码。
1.先安装vuex
npm install vuex --save
2.创建一个store的文件夹,新建store.js文件。我们需要在这个文件中引入Vue和Vuex,并且需要安装Vuex
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ count:1 } const mutations={ add(state,n){ state.count+=n; }, reduce(state){ if(state.count<=1){ state.count=1; }else{ state.count-=1; } } } export default new Vuex.Store({ state, mutations })
State中放我们需要共享的数据,mutations是用来处理数据的方法。
3.创建视图组件来调用store中的方法
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.count}}</h3>
<div>
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
</div>
</template>
<script>
import store from "@/store/store"
export default{
data(){
return{
msg:'Hello Vuex'
}
},
store,
computed:{
count(){
return this.$store.state.count
}
}
}
</script>
<style scoped>
</style>
这样一个简单的vuex例子就完成了。
我们还可以有别的写法来完成上述的功能
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={
count:1
}
const mutations={
add(state,n){
state.count+=n;
},
reduce(state){
if(state.count<=1){
state.count=1;
}else{
state.count-=1;
}
}
}
const actions={
"INC":(store)=>{
store.commit('add',10)
},
"RED":(store)=>{
store.commit('reduce')
}
}
export default new Vuex.Store({
state,
mutations
actions
})
在store.js中定义一个actions用来负责把mutations中的逻辑发送给视图
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.count}}</h3>
<div>
<button @click="add">+</button>
<button @click="reduce">-</button>
</div>
</div>
</template>
<script>
import store from "@/store/store"
export default{
data(){
return{
msg:'Hello Vuex'
}
},
store,
computed:{
count(){
return this.$store.state.count
}
},
methods:{
add:function(){
this.$store.dispatch("INC")
},
reduce:function(){
this.$store.dispatch("RED")
}
}
}
</script>
<style scoped>
</style>
不足之处,希望多多指正~~