简介:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
==>(因为是可预测的,所以状态的修改,需要专门的修改方式)
Vuex 和单纯的全局对象有以下两点不同:
1、Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2、你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
核心概念:
state:存储状态值;
mutations:状态值的改变方法,操作状态值,提交mutations是更改Vuex状态的唯一方法;
actions:actions用于处理异步事件,最后还是需要提交mutations来改变state;
getter:
modules:
总结:
正常的Vue事件流程是:actions(点击事件)-->state(状态值改变)-->view(视图改变)
Vuex的事件流程多了个mutations过程:actions(点击事件)-->mutations(事件提交)-->state(store状态值改变)-->view(视图改变)(Vuex的state状态值修改,需要专门提交机制(commit)的来修改mutations)
使用思路:安装vuex插件(cnpm install vuex --save),然后在src目录下创建store文件夹,文件夹下创建index.js、actions.js、mutations.js、mutations-types.js和getters.js文件
==> store/index.js文件下进行全局变量state的定义、getters、acations、mutations文件的引入和new Vuex.
Store({})初始化声明:
import Vue from 'vue'
import Vuex frome 'vuex'
Vue.use(Vuex)
import action frome './actions'
import getters frome './getters'
import mutations frome './mutations'
const state={
variableA = "这是变量A",
variableb = ["这是变量数组B"]
}
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
==> store/action.js文件就是用来调用mutations.js内定义的函数:
import {
MUTATION_FUCA,
MUTATION_FUCB
} from './mutations-types'
export default{
/*一般写法:context指代store对象,但是不完全等价于store对象*/
FucA(context){
console.log(context.state.variableA ) //打印出"这是变量A"
/*这里的commit()的括号内容需是字符串,因而引入mutations-types文件内的字符串常量*/
context.commit(MUTATION_FUCA)
}
/*参数解构写法*/
FucB({commit,state}){
console.log(state.variableA ) //打印出"这是变量A"
commit(MUTATION_FUCA)
}
}
==> store/mutations-types.js文件就是用来进行mutations常量名的声明,可有可无,主要就是为了多人合作时,方便查看修改:
export const MUTATION_FUCA = 'MUTATION_FUCA'
export const MUTATION_FUCB = 'MUTATION_FUCB'
==> store/mutations.js文件用来修改全局变量的state,只有它才能直接修改state变量
import {
MUTATION_FUCA,
MUTATION_FUCB
}from 'mutations-types'
export default{
//一般写法:
mutationB(state){
state.variableB="B我被修改了";
}
//es6的计算属性命名风格写法
[MUTATION_FUCA](state){
state.variableA="A我被修改了";
}
}
==>getters文件相当于封装一个变量方法,直接调用该方法,就能直接获取state的指定变量,这种方法比直接通过computed: {doneTodosCount () {return this.$store.state.todos.filter(todo => todo.done).length}}
要好,如果需要在其它组件使用这个变量函数,要么每个组件内都复制申明这个函数,要么抽取成一个全局函数,然后在需要用到的地方引用。
const activeNote = state => state.activeNote;
export default{
activeNote
}
==>组件内使用上述的方法:state和getters在computed内声明,actions在methods内声明
computed: {
...mapGetters([
'filteredNotes'
]),
...mapState([
'show',
'activeNote'
]),
searchNotes() {
if (this.search.length > 0) {
return this.filteredNotes.filter((note) => note.title.toLowerCase().indexOf(this.search) > -1);
} else {
return this.filteredNotes;
}
}
}
methods: {
...mapActions({
update: 'updateNote'
}),
updateNote() {
this.update({
note: this.currentNote
});
}
}