vuex--day71--vuex 写的求和案例
1.store/index.js
//改文件用于创建vuex 最为核心的 store
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备actions ---用于响应组件中的动作
const actions={
// 没有逻辑 可以直接 mutations
// jia(conext,value){
// //console.log("actions里面的jia被调用了",conext,value)
// conext.commit('JIA',value)
// },
// jian(conext,value){
// //console.log("actions里面的jian被调用了",conext,value)
// conext.commit('JIAN',value)
// },
incrementOdd(conext,value){
//console.log("actions里面的incrementOdd被调用了",conext,value)
if(conext.state.sum%2){
conext.commit('JIA',value)
}
},
incrementWait(conext,value){
//console.log("actions里面的incrementWait被调用了",conext,value)
setTimeout(() => {
conext.commit('JIA',value)
}, 500);
},
}
//准备mutations--用于操作数据(state)
const mutations={
JIA(state,value){
//console.log("mutations里面的jia被调用了",state,value)
state.sum+=value
},
JIAN(state,value){
//console.log("mutations里面的jian被调用了",state,value)
state.sum-=value
},
}
//准备state --用于存储数据
const state={
sum:0
}
// 创建store 暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
2. 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>
<option value="4">4</option>
</select>
<button @click="increment">+</button>
<button @click="dectement">-</button>
<button @click="incrementOdd">当前和为奇数在加</button>
<button @click="incrementWait">等一等在加</button>
</div>
</template>
<script>
export default {
name:'Count',
data(){
return {
n:1,
sum:0
}
},
mounted(){
console.log('countvue',this)
},
methods:{
increment(){
//this.$store.dispatch('jia',this.n)
this.$store.commit('JIA',this.n)
},
dectement(){
//this.$store.dispatch('jian',this.n)
this.$store.commit('JIAN',this.n)
},
incrementOdd(){
this.$store.dispatch('incrementOdd',this.n)
},
incrementWait(){
this.$store.dispatch('incrementWait',this.n)
}
}
}
</script>
<style>
button{
margin-left: 10px;
}
</style>
3. App.vue
<template>
<div>
<Count></Count>
</div>
</template>
<script>
import Count from './components/Count.vue';
export default {
name: 'App',
components:{
Count
},
mounted(){
console.log('appvue',this)
}
}
</script>
<style>
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本