首先在 src 下创建 store/index.js
// 导入 vuex
import Vuex from 'vuex'
// 创建仓库 store
const store = new Vuex.Store({
// 相当于vue 里 data return,需要提前声明需要的变量
state () {
return {
count: 2
}
},
mutations: {
//第一个参数state 相当于vue里的 this,data是调用方法时传的值
increment (state,data) {
state.count = data;
}
}
});
// 导出仓库
export default store
在main.js里调用
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'.
// 引入创建的storejs
import store from './store'
createApp(App).use(store).mount('#app');
其他组件使用
//直接在标签中使用
<p>数字 {{ $store.state.count }}<p>
// 也可以在js里使用
export default {
data() {
return {
nowCount:''
}
},
methods: {
increaseCount(){
this.nowCount = $store.state.count;
}
},
}
更改数据
clickMsg(){//第一个参数是 store/index.js 定义的方法名,第二个参数是接受的参数
this.$store.commit('increment',5)
}