正式开始
npm install vuex –save
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
创建一个store实例
const store = new Vuex.Store({
// vuex 中的一些状态
state: { count:0 },
// vuex 中改变状态的方法
mutations: {
fn2(state){ state.count++; }
}
});
在main.js中 ,用
import store from "./modules/store.js"引入
再把store注册一下
new Vue({
store,
el:'#app',
render:h=>h(App)
})
在其他组件中使用
<template>
<div @click="fn">{{count}}</div>
</template>
<script>
export default {
data () { return { } },
computed: {
count(){
// 把vuex中的状态赋给count
return this.$store.state.count
}
},
methods: {
fn(){
// 调用vuex中改变状态的方法
this.$store.commit('fn2');
}
}
}
</script>