Vuex是用来存放全局数据,并管理组件之间的数据传递。
1.安装
npm install --save vuex
2.引用
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
3.vuex有4个核心功能:state mutations getters actions
var myStore = new Vuex.Store({ //创建vuex管理器。
state:{
//存放组件之间共享的数据
name:"jjk"
},
mutations:{
//显式的更改state里的数据
},
getters:{
//获取数据的方法
},
actions:{
//
}
});
new Vue({
el:"#app",
data:{name:"jjk"},
store:myStore,
mounted:function(){
console.log(this)//控制台
}
})
4.写了个demo,代码如下:
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
mutations: {
INCREMENT(state) {
state.count++;
},
DECREMENT(state) {
state.count--
},
INCREMENT_WITH_VALUE(state, value){
state.count +=value;
}
},
getters:{
show_value(state){//这里的state对应着上面这个state
return state.count;
}
},
actions: {
increment(context){
context.commit("INCREMENT")
},
decrement({commit}){
commit("DECREMENT")
},
incrementWithValue({commit}, value){
commit("INCREMENT_WITH_VALUE", parseInt(value))
}
}
})
// 简写,解构
// increment({commit}){
// commit("INCREMENT")
// },
<template>
<div>
<div>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
<div>
<h2>{{show_value}}</h2>
<input type="text" v-model="incrementValue">
<button @click="incrementWithValue">increment</button>
</div>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations,mapActions } from 'vuex'
export default {
data() {
return {
incrementValue: 0
}
},
computed:{
...mapGetters(['show_value']),
},
methods: {
...mapActions(["increment","decrement"]),
incrementWithValue() {
this.$store.dispatch("incrementWithValue", this.incrementValue)
}
}
}
</script>
<template>
<div>
<div>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
<div>
<h2>{{show_value}}</h2>
<input type="text" v-model="incrementValue">
<button @click="incrementWithValue">increment</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
incrementValue: 0
}
},
computed:{
show_value(){
return this.$store.state.count;
}
},
methods: {
increment(){
this.$store.dispatch("increment")
},
decrement(){
this.$store.dispatch("decrement")
},
incrementWithValue() {
this.$store.dispatch("incrementWithValue", this.incrementValue)
}
}
}
</script>