Vuex 并不限制你代码结构。但是, 它规定一些需要遵守的规则
- 应用层级的状态,应该集中到单个store对象中
- 提交mutation是更改状态的唯一方法,并且这个过程是同步的
- 异步逻辑都应该封装到action内
遵循以上规则,如何组织代码随便。如果store文件太大,可以将action,mutation和getter分割出来 ,形成单独的文件
State 单一状态的树
储存在Vuex中的数据和Vue实例的数据遵循相同的规则,例如对象必须是纯粹的
Vue组件获取store实例中的值
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
每当 store.state.count 变化,都会重新求取计算属性,并且触发更新关联的DOM
Getter
Vuex 允许我们在store中定义’getter’(可以认为是store的计算属性),getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
对象风格
store.commit({
type: 'increment',
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
Mutation 需遵守 Vue 的响应规则
1 最好提前在你的 store 中初始化好所有所需属性。
2 当需要在对象上添加新属性时,你应该
Mutation 必须是同步函数
Action
1 Action 提交的是 mutation,而不是直接变更状态。
2 Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
异步
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
自定义的全局方法
Vue.prototype.getTitle = {
title:'',
isBack: true,
isAdd: false,
};
Vue.prototype.baseUrl = function () {
return 'http://csdn.net';
};
可以在项目的src 目录里面 新建一个 lib目录 。lib目录里创建一个 config目录, 然后在config目录里新建一个config.js文件.
src\lib\config/config.js
config.js文件里写上
export default {
install(Vue,options)
{
Vue.prototype.baseUrl = function () {
return '111';
};
Vue.prototype.getTitle = {
title:'',
isBack: true,
isAdd: false,
};
Vue.prototype.showFootTab = {
isShow:false,
active:0,
}
}
}
在 根目录下的 main.js中 添加下面两行代码即可
import config from './lib/config/config.js'
Vue.use(config);
使用方法
(1)直接在模版中调用
<template>
<div>
{{getTitle.title}}
</div>
</template>
(2)js代码中使用
this.getTitle