- 1.安装vuex :
- npm i vuex
- 1.在store.js里引入vuex ,注册vuex:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);
- 3.定义数据
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 1. 存数据
var state = {
count: 1
}
// 2.方法 改变state里面的数据
var mutations = {
inCount() { //加
++state.count
},
inCount_() { //减
--state.count
}
}
//实例化vuex.store
const store = new Vuex.Store({
state,
mutations
})
export default store;
- 3.获取state里面的数据
{{this.$store.state.count}}
- 4.获取方法
incCount(){ this.$store.commit('inCount') }
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 1. 存数据
var state = {
count: 1
}
// 2.方法 改变state里面的数据
var mutations = {
inCountAdd() { //加
++state.count
},
inCount_() { //减
--state.count
}
}
//实例化vuex.store
const store = new Vuex.Store({
state,
mutations
})
export default store;
home.vue
<template>
<div class="hello">
home
{{this.$store.state.count}}
<button @click="incCount">增加</button>
</div>
</template>
<script>
import store from "../vuex/store";
export default {
methods: {
incCount() {
this.$store.commit("inCountAdd");//增加
}
},
store,
data() {}
};
</script>
<style scoped>
</style>
new.vue
<template>
<div>
{{this.$store.state.count}}
<br />
<button @click="icCoount_">减</button>
</div>
</template>
<script>
import store from "../vuex/store";
export default {
store,
methods: {
icCoount_() {
this.$store.commit("inCount_");//减
}
}
};
</script>
<style lang="scss" scoped>
</style>