1、安装vuex
npm install vuex --save
2、模块引用vuex,创建store文件夹创建index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
num: 0,
typeData: {}
},
mutations: {
increment (state) {
state.count++
},
numcount (state,mes) {
state.num = mes
},
typeDataSum (state,mes) {
state.typeData = mes
}
}
})
export default store;
3、在main.js中引入store文件
import store from "./store"
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
4、在页面中直接引用就可以
<template>
<div>
{{ this.$store.state.count }} {{ count }} {{ num }} {{ typeData.a }}
</div>
</template>
<script>
import { mapState } from "vuex"
export default {
data() {
return {
count: this.$store.state.count // 第一种引用方式
}
},
computed:{
// 第二种引用方式
...mapState({
count: (state) => state.count,
num: (state) => state.num,
typeData: (state) => state.typeData
})
},
created() {
this.$store.commit('increment');
this.$store.commit('numcount',10);
this.$store.commit('typeDataSum',{a:2});
}
}
</script>