vuex学习暂存

new_branch1
roger 2 years ago
parent 9287db0544
commit 58b5ae9e08
  1. 17
      20_脚手架/vue_code/src/components/Count.vue
  2. 29
      20_脚手架/vue_code/src/store/index.js

@ -1,6 +1,6 @@
<template>
<div>
<h1>当前求和为: {{sum}}</h1>
<h1>当前求和为: {{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
@ -18,8 +18,7 @@ export default {
name: "Count",
data() {
return {
n: 1,
sum: 0
n: 1
}
},
mounted() {
@ -27,20 +26,16 @@ export default {
},
methods: {
add() {
this.sum += this.n
this.$store.commit('vuexAdd', this.n)
},
sub() {
this.sum -= this.n
this.$store.commit('vuexSub', this.n)
},
addOdd() {
if (this.sum % 2) {
this.sum += this.n
}
this.$store.dispatch('vuexAddOdd', this.n)
},
addWait() {
setTimeout(()=>{
this.sum += this.n
}, 500)
this.$store.dispatch('vuexAddWait', this.n)
}
}

@ -7,12 +7,33 @@ import Vuex from 'vuex'
// 应用Vuex插件
Vue.use(Vuex)
// 准备actions-用于响应组件中的动作
const actions = {}
// 准备actions-用于响应组件中的动作,业务逻辑需要写到actions中
const actions = {
vuexAddOdd(context, value) {
if (context.state.sum % 2) {
context.commit('vuexAdd', value)
}
},
vuexAddWait(context, value) {
setTimeout(() => {
context.commit('vuexAdd', value)
}, 1000
)
}
}
//准备mutations-用于操作数据
const mutations = {}
const mutations = {
vuexAdd(state, value) {
state.sum += value
},
vuexSub(state, value) {
state.sum -= value
}
}
//准备state-用于存储数据
const state = {}
const state = {
sum: 0
}
// 创建并导出store
export default new Vuex.Store({

Loading…
Cancel
Save