1,146
社区成员
发帖
与我相关
我的任务
分享
1.npm i vuex
//注意:(vue3只能安装npm i vuex@4)
//注意:(vue3只能安装npm i vuex@3)
//2.store文件夹使用Vue.use(Vuex)
//(1)src文件夹下创建 store文件夹
//(2)引入文件Vue 和 Vuex因为Vue.要使用Vuex
improt Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//(3)准备好actions/mutations/state三个对象
const actions = {}
const mutations = {}
const state = {}
//(4)然后创建并暴露store
export default new Vuex.Store({
actions ,
mutations,
state,
})
//引入store
import Store from './store'
//new Vue实例中添加一个Store配置项
new Vue({
el:'#app',
render:h => h(App),
Store,
beforeCreate(){
Vue.prototype.$bue = this
}
})
<template>
<div>
<h2>当前求和为:4</h2>
<select v-model.number='n'>
//也可以通过v-bind:value控制字符串'1'改动时变成string数字
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<button @click='add'>+</button>
<button @click='addDe'>-</button>
<button @click='addOdd'>当前求和为奇数在加</button>
<button @click='addWaite'>等一等在加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods:{
add() {
this.$store.commit('JIA',this.n)
},
addDe() {
this.$store.commit('JIAN',this.n)
},
addOdd() {
this.$store.dispatch('addOdd'.this.n)
},
addWaite() {
this.$store.dispatch('addWaite'.this.n)
},
}
}
</script>
//准备actions服务员接受客人提的要求dispatch(要求)
const actions = {
addOdd(context,value) {
if(context.state.sum){context.$commit('JIA',value)}},
addWaite(context,value) {
setTimeout(() =>{context.$commit('JIA',value)},500)
}},
// 准备mutations厨师操作数据按照条件变更
const mutations = {
JIA(state,value) {state.sum += value},
JIAN(state,value) {state.sum -= value}
}
//准备state存储数据
const state = {
sum:0,
}