1、vuex是什么:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
2、学习准备:
1)、vuex中文官网
2)、搭建好vue脚手架,vue init webpack <projectName> 文件名不建议使用‘vuex’,因为创建好脚手架后使用vuex需要进行npm安装。这个时候会检测到你使用的项目名Name为:”vuex“,然后报错,网上有一个这个问题,如果遇到可移步;
3)、安装vuex:
npm install vuex --save
yarn add vuex
3、使用:
1)、在vuecli目录下创建一个store目录并新建一个index.js文件。以下是index.js文件内容
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state:{
count: 0,
cityName: "北京",
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
}
})
export default store
2)、引入存储并注入
在main.js中引入我们刚刚创建的index.js文件:
import store from './store/index.js'
并且注入存储:
new Vue({
store,
render: h => h(App)
}).$mount('#app-box')
3)、使用测试
State
在vue页面中进行测试使用,检验是否能获取到store中的参数
在methods中随便写一个方法,进行访问(通过属性访问)
console.log(this.$store.state.cityName);
console.log(this.$store.state.todos.length);
也可以在computed中直接通过一下进行访问并渲染到页面中
computed: {
cityName() {
return this.$store.getters.cityname;
}
}
在html中书写:
<span @click="changeCity">{{cityName}}</span>
Getter
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤等;我们可以 在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。例如: // vue页面中调用一下方法获取return的值
getters: {
cityname(state) {
return state.cityName + "市区"
},
upperOwner(state) {
return state.owner.slice(0, 1).toUpperCase() + state.owner.slice(1)
},
doneTodos(state) {
return state.todos.filter(a => a.done == true) //获取到done为true的元素
},
getTodoById: (state) => (id) => {
return state.todos.filter(a => a.id == id) //获取到id为指定id的元素
}
},
vue页面中调用getters方法的两种方式:
属性访问:
console.log(this.$store.getters.doneTodos);
方法访问(红色字store需要先进行导入:“import store from "../store/index.js";")):
console.log(store.getters.getTodoById(2)) //获取到id为指定id的元素
mutation
store.commit
传入额外的参数,即 mutation 的 载荷(payload): mutations: {
// 函数参数1 state:state状态
// 函数参数2 自定义参数
// 必须是同步函数
getCityName(state, newVal) {
state.cityName = newVal
console.log(state.cityName)
}
},
vue页面中
调用
store.commit
方法进行提交mutation
store.commit("getCityName", "北京");
Action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
actions: {
// context 上下文 只带当前store对象
// param 参数
getCityName(context,param){
setTimeout(function(){
// 修改state 依旧需要提交mutations 才可以改变
context.commit('getCityName',param)
}, 1000);
}
}
vue页面中调用:在组件中使用 this.$store.dispatch('xxx')
分发 action
setTimeout(() => {
this.$store.dispatch("getCityName", 'action触发');
}, 3000);
下面是主要代码:
备注:state的mapState辅助函数,getter的mapGetters辅助函数,Mutation的mapMutations辅助函数此处没有,可移步官网查看核心概念对应学习