Vue.js状态管理模式 Vuex
vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装、使用 vuex
首先我们在 vue.js 2.0 开发环境中安装 vuex :
npm install vuex --save
然后 , 在 main.js 中加入 :
import vuex from 'vuex'
Vue.use(vuex);
const store = new vuex.Store({//store对象
state:{
show:false,
count:0
}
})
再然后 , 在实例化 Vue对象时加入 store 对象 :
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:
store.commit('increment')
console.log(store.state.count) // -> 1
State
在 Vue 组件中获得 Vuex 状态
从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState 辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性:
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组:
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
Getter
getters 和 vue 中的 computed 类似 , 都是用来计算 state 然后生成新的数据 ( 状态 ) 的,就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
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)
}
}
})
通过属性访问
Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也可以接受其他 getter 作为第二个参数:
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
组件中使用:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。
通过方法访问
通过方法访问
你也可以通过让 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 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
注册:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
调用:
store.commit('increment')
提交载荷(Payload)
你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
如果提交多个参数,必须使用对象的形式进行提交
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
注:mutations里的操作必须是同步的;
Action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action 通过 store.dispatch 方法触发:
store.dispatch('increment')
在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
对象形式传参:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
相关文章
- Vue.js快速介绍-超级马里奥像素艺术
- vue.js响应式原理解析与实现
- 使用 Vuex + Vue.js 构建单页应用
- JS框架_(Typed.js)彩色霓虹灯发光文字动画
- JS框架_(Vue.js)带有星期日期的数字时钟
- VUE - vue.runtime.esm.js?6e6d:619 [Vue warn]: Do not use built-in or reserved HTML elements as component i
- [Nuxt] Update Vuex State with Mutations and MapMutations in Vue.js
- [Vue] Update Attributes, Classes and Styles in Vue.js with v-bind
- [Vue] Preload Data using Promises with Vue.js and Nuxt.js
- vue.js开发SPA常见问题及解决方法
- vue+elementui项目打包后样式变化问题
- 从安装node js到构建一个vue并启动它
- [Vue-rx] Handle Image Loading Errors in Vue.js with RxJS and domStreams
- [Vue] Build Vue.js Apps with the Vue-CLI and Nuxt.js
- vue.js 3.2.22:用@vueuse/core实现图片懒加载(@vueuse/core@7.0.3)
- vue.js 3.2.20: 用photoswipe实现图片的浏览:增加切换动画和自动播放(photoswipe@4.1.3)
- vue.js 3.0.5:用vue-i18n开发i18n国际化功能(vue-i18n@9.2.0)
- Vue Nuxtjs Cannot set property 'render' of undefined解决方法
- vue 的 render 函数的用法:new Vue({ render: h => h(App), }).$mount(‘#app‘)
- vue项目JS播放音频音效和背景音乐
- Vue.js 组件(component)demo小案例
- ElementUI+VUE 在使用ElementUI日期选择器时大于当前月份的日期不可选,默认日期
- vue 项目中引用百度地图
- 关于购物车添加按钮的动画(vue.js)
- CDN方式Vue组件注册
- vue.js项目打包报错Error: You appear to be using a native ECMAScript module configuration file
- babel配置项目目录支持转换es6语法,引入非项目目录js后,引入Js转换无效
- vue.js中引入图片
- 171:vue+openlayers 获取两个多边形的交集、差集、并集
- 065:vue+openlayers显示不同颜色point(示例代码)
- 055:vue+openlayers的select-modify-snap功能展示(代码示例)
- 学会在Vue项目中插入高德地图JS API与地图的相关设置,看这一篇就够了~(保姆级精简教学)
- vue本地存储、获取自定义data-id、获取链接url参数、页面跳转返回、修改页面title
- vue+element ui+腾讯云开发打造会员管理系统之实战教程(二)环境搭建
- vue卫星应用示例从0到1部署运行环境