Vue之共享V之简单入门
一、项目结构
二、store文件下index.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const actions = {
//定义奇数再加法
xPlusBySumOdd(context, value) {
if (this.state.sum % 2)
context.commit("XPlus", value)
},
//定义等一会儿再加法
xPlusWait(context, value) {
setTimeout(()=>{
context.commit("XPlus", value)
},500)
},
}
const mutations = {
//定义加法实现
XPlus(state, value) {
return state.sum += value;
},
//定义减法实现
XSubtract(state, value) {
return state.sum -= value;
}
}
const state = {
sum: 0
}
export default new Vuex.Store({
actions,
mutations,
state
})
三、main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
四、组件count.vue
<template>
<div>
<h1>{{ $store.state.sum }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="plus">+</button>
<button @click="subtract">-</button>
<button @click="plusBySumOdd">和奇数再加</button>
<button @click="plusWait">等一会儿再加</button>
</div>
</template>
<script>
export default {
name: "Count",
data() {
return {
n: 0
}
},
methods: {
//定义加法
plus() {
this.$store.commit("XPlus", this.n)
},
//定义减法
subtract() {
this.$store.commit("XSubtract", this.n)
},
//定义和为奇数再加法
plusBySumOdd() {
this.$store.dispatch("xPlusBySumOdd", this.n)
},
//定义等等再加法
plusWait() {
this.$store.dispatch("xPlusWait", this.n)
}
}
}
</script>
五、APP代码
<template>
<div id="app">
<count></count>
</div>
</template>
<script>
import Count from "./components/Count";
export default {
name: 'App',
components: {
Count
}
}
</script>
六、效果图
七、总结
如果没有复杂业务逻辑或异步可以直接调用mutation中方法。
this.$store.commit("XPlus", this.n)
反之需调用action 中的方法
this.$store.dispatch("xPlusBySumOdd", this.n)