什么是vuex?
vuex官网的解释是:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
从上图可以很好看出这几个属性之间的调用关系(不过官方图没有画出getters的使用)
可以看出:
组件Vue Component通过dispatch来调用actions提供的方法
而actions除了可以和api打交道外,还可以通过commit来调mutations提供的方法
最后mutaions将数据保存到state中
当然,Vue Components还以通过getters提供的方法获取state中的数据
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
let store = new Vuex.Store({
// 1. state
state:{
city:"城市名"
},
// // 2. getters
getters:{
// 参数列表state指的是state数据
getCityFn(state){
return state.city;
}
},
// 3. actions
// 通常跟api接口打交道
actions:{
// 设置城市信息
// 参数列表:{commit, state}
// state指的是state数据
// commit调用mutations的方法
// name就是调用此方法时要传的参数
setCityName({commit,state}, name){
// 跟后台打交道
// 调用mutaions里面的方法
commit("setCity", name);
}
},
// 4. mutations
mutations:{
// state指的是state的数据
// name传递过来的数据
setCity(state, name){
state.city = name;//将传参设置给state的city
}
}
});
export default store;
4. 在main.js中引用vuex
就可以在组件使用this.$store来调用方法
import store from './store/store.js';
5. 如何在组件中使用
主页组件Homepage.vue
组件页面中的city数据通过this.$store.getters来获取store.js所写getters提供的getCityFn方法
<template>
<div class="home">
<h1>{{city}}</h1>
<!-- 按钮导航 -->
<router-link tag='button' to="/citylist">获取城市列表</router-link>
</div>
</template>
<script>
export default {
data () {
return {
}
},
computed:{
city:function() {
// 通过vuex的getters方法来获取state里面的数据
return this.$store.getters.getCityFn;
}
}
}
</script>
城市列表组件CityList.vue
当点击列表的时候,通过this.$store.dispatch来调用store.js中actions所提供的setCityName方法,并将城市名传参过去
<template>
<div class="city">
<ul>
<li v-for="(item,index) in cityArr" @click="backFn(index)">
<h2>{{item}}</h2>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
cityArr:['北京','上海','广州','深圳','茂名','张家界','清远','汕头','佛山']
}
},
methods:{
backFn : function(index){
// 调用vuex的ations设置城市的值
this.$store.dispatch("setCityName", this.cityArr[index]);
//返回到首页
this.$router.push("/");
}
}
}
</script>