用过vuex之后感觉它就是一个大仓库,大的状态机,记录了全局变量的状态信息,当我们想改变嵌套组件的值或者传值的过程中可以用store来进行管理
首先看看官方的解释和科普:
显示组件发送 dispatch事件到Store的Actions层 ,这一层相当于vue组件的事件机制,里面包含的操作可以是任何的异步操作,提交mutaion不直接改变状态:
//调用mutations用的,包含任何异步操作 提交mutation不直接改变状态
const actions = {
//参数的解构
aAdd({commit,getters}){
// console.log("context is ",context);
commit('add',6);
console.log("getters is ",getters);
},
put({commit}){
commit('puts');
}
}
actions的操作是将事件传递给Mutations层去处理,mutation相当于vue组件的methods对象,mutation去处理state层的数据:
但是mutations不可以处理任何的异步操作
//相当于methods 里面的方法必须是同步的方法
const mutations = {
add(state,n){
console.log("n is ",n);
console.log("state.count is ",state.count);
state.count += n;
console.log("加之后的count is",state.count);
},
reduce(state,n){
state.count -= n;
},
puts(state){
console.log("puts events");
}
}
//相当于data
const state = {
count : 0
}
这里是index.vue组件的实例:
显示根目录下创建Store文件夹:
index.js
//index页面的状态管理器
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//相当于data
const state = {
count : 0
}
//相当于methods 里面的方法必须是同步的方法
const mutations = {
add(state,n){
console.log("n is ",n);
console.log("state.count is ",state.count);
state.count += n;
console.log("加之后的count is",state.count);
},
reduce(state,n){
state.count -= n;
},
puts(state){
console.log("puts events");
}
}
//相当于computed
const getters = {
//state的属性发生改变的时候就会执行该getters方法
count2 (state){
console.log("调用了count2方法");
// return state.count += 100;
}
}
//调用mutations用的,包含任何异步操作 提交mutation不直接改变状态
const actions = {
//参数的解构
aAdd({commit,getters}){
// console.log("context is ",context);
commit('add',6);
console.log("getters is ",getters);
},
put({commit}){
commit('puts');
}
}
export default new Vuex.Store({
state,
mutations,
getters,
actions
})
index.vue组件
<template>
<div class="index-page-con">
{{message}}
<a href="cart.html">进入购物车界面</a>
<c-head></c-head>
count : {{$store.state.count}}<br>
<!-- count:{{count}} -->
count2 : {{$store.getters.count2}}<br>
<button @click="$store.commit('add',10)">+</button>
<button @click="reduce(2)">-</button>
actions调用mutation的方法<button @click="aAdd">加</button>
<button @click="put">put</button>
</div>
</template>
<script>
import head from './head'
import store from '@/store/index'
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex';
export default {
props : {
text : String,
sos : String
},
created() {
console.log("index created");
},
store : store,
components : {
'c-head' : head
},
mounted() {
console.log("this is ",this);
console.log("this.text is ",this.text);
},
data(){
return {
message : "index's message in index.vue",
}
},
methods : {
//使用状态机统一管理全局变量的状态
//将this.add()映射为this.$store.commit('add'),this.reduce 映射为this.$store.commit('reduce')
...mapMutations(['add','reduce']),
//将this.add 映射为this.$store.commit('increment')
...mapActions(['aAdd','put'])
}
}
</script>
<style lang="less" scoped>
</style>