1.创建一个js文件 ,可以全局注册页可以在单个组件引用,我这里创建vuex文件夹,创建store.js
import Vue from \'vue\';
import Vuex from \'vuex\';
Vue.use(Vuex);
//数据源
const state={
count:1
};
//getters属性 暂时没用到
const getters ={
fn:function(state){
return state.count+=100;
}
};
//固定写法 修改状态同步
const mutations ={
add(state){
console.log(\"1\")
state.count++;
},
reduce(state){
state.count--;
}
};
//修改状态 异步 调用了mutations里的方法
const actions = {
addA(context){
console.log(\"2\")
context.commit(\'add\',10)
},
redA({commit}){
commit(\'reduce\',10)
},
};
//这里一定要记得导出
export default new Vuex.Store({
state,getters,mutations,actions,
})
然后在需要用到这个数据的组件里引入
import store from \'../vuex/store\';
//import { mapGetters } from \'vuex\'
export default {
store, //这里一定要调用
data(){
return{
msg:23,
}
},
computed:{
//...mapGetters([\"fn\"]),
count1(){
return store.state.count;
// return this.$store.getters.count;
}
},
<h3>{{$store.state.count}}</h3> //1 先展示 接下来修改
<button @click=\"$store.commit({type: \'add\'})\">点击加1</button>
<button @click=\"$store.commit(\'reduce\')\">点击减一</button>
//这里是调用mutations 里的方法
<button @click=\"add2()\">++++++++</button>
<button @click=\"red2()\">----------</button>
methods{
adds(){
this.$store.dispatch(\'addA\',2)
},
reds(){
this.$store.dispatch(\'redA\')
},
}
//这里是 actions 里的方法
继续阅读与本文标签相同的文章
下一篇 :
第一个爬虫程序
-
【云栖活动】架构师、产品经理一对一座谈会/WORKSHOP-已截止
2026-05-18栏目: 教程
-
MySQL入门书籍和方法分享
2026-05-18栏目: 教程
-
树莓派4&阿里云物联网平台上云开发实操
2026-05-18栏目: 教程
-
最新115道华为、京东、滴滴、美团精选Java面试题整理
2026-05-18栏目: 教程
-
吴伯凡:谁在重新定义我们的城市
2026-05-18栏目: 教程
