在 Vue 的单页面应用中使用,需要使用Vue.use(Vuex)调用插件。
使用非常简单,只需要将其注入到Vue根实例中。

import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 可以包含异步操作
// context 是一个与 store 实例具有相同方法和属性的 context 对象
}
}
})
// 注入到根实例
new Vue({
el: '#app',
store,
template: '<App/>',
components: { App }
})

然后改变状态:

this.$store.commit('increment')

Vuex 主要有四部分:

  1. state:包含了store中存储的各个状态。
  2. getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
  3. mutation: 一组方法,是改变store中状态的执行者。
  4. action: 一组方法,其中可以含有异步操作。

state

Vuex 使用 state来存储应用中需要共享的状态。为了能让 Vue 组件在 state更改后也随着更改,需要基于state创建计算属性。

const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count // count 为某个状态
}
}
}

getters

类似于 Vue 中的 计算属性,可以在所以来的其他 state或者 getter改变后自动改变。
每个getter方法接受 state和其他getters作为前两个参数。

getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
}

mutations

前面两个都是状态值本身,mutations才是改变状态的执行者。mutations用于同步地更改状态

// ...
mutations: {
increment (state, n) {
state.count += n
}
}

其中,第一个参数是state,后面的其他参数是发起mutation时传入的参数。

this.$store.commit('increment', 10)

commit方法的第一个参数是要发起的mutation名称,后面的参数均当做额外数据传入mutation定义的方法中。
规范的发起mutation的方式如下:

store.commit({
type: 'increment',
amount: 10 //这是额外的参数
})

额外的参数会封装进一个对象,作为第二个参数传入mutation定义的方法中。

mutations: {
increment (state, payload) {
state.count += payload.amount
}
}

actions

想要异步地更改状态,需要使用actionaction并不直接改变state,而是发起mutation

actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}

发起action的方法形式和发起mutation一样,只是换了个名字dispatch

// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})

action处理异步的正确使用方式

想要使用action处理异步工作很简单,只需要将异步操作放到action中执行(如上面代码中的setTimeout)。
要想在异步操作完成后继续进行相应的流程操作,有两种方式:

  1. action返回一个 promise
    dispatch方法的本质也就是返回相应的action的执行结果。所以dispatch也返回一个promise

    store.dispatch('actionA').then(() => {
    // ...
    })

2. 利用async/await。代码更加简洁。

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}

  

各个功能与 Vue 组件结合

  将stategetter结合进组件需要使用计算属性:

computed: {
count () {
return this.$store.state.count
// 或者 return this.$store.getter.count2
}
}

mutationaction结合进组件,需要在methods中调用this.$store.commit()或者this.$store.commit():

methods: {
changeDate () {
this.$store.commit('change');
},
changeDateAsync () {
this.$store.commit('changeAsync');
}
}

为了简便起见,Vuex 提供了四个方法用来方便的将这些功能结合进组件。

  1. mapState
  2. mapGetters
  3. mapMutations
  4. mapActions

示例代码:

import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

// ....
computed: {
localComputed () { /* ... */ },
...mapState({
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
count(state) {
return state.count + this.localCount
}
}),
...mapGetters({
getterCount(state, getters) {
return state.count + this.localCount
}
})
}
methods: {
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为`this.$store.commit('increment')`
}),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}

如果结合进组件之后不想改变名字,可以直接使用数组的方式。

methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
}

将 store分割为模块。

可以将应用的store分割为小模块,每个模块也都拥有所有的东西:stategettersmutationsactions
首先创建子模块的文件:

// initial state
const state = {
added: [],
checkoutStatus: null
}
// getters
const getters = {
checkoutStatus: state => state.checkoutStatus
}
// actions
const actions = {
checkout ({ commit, state }, products) {
}
}
// mutations
const mutations = {
mutation1 (state, { id }) {
}
}
export default {
state,
getters,
actions,
mutations
}

然后在总模块中引入:

import Vuex from 'vuex'
import products from './modules/products' //引入子模块 Vue.use(Vuex)
export default new Vuex.Store({
modules: {
products // 添加进模块中
}
})

其实还存在命名空间的概念,大型应用会使用。需要时查看文档即可。Vuex的基本使用大致如此。

作者:胡不归vac
链接:https://www.jianshu.com/p/aae7fee46c36
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Vuex基本使用的总结--转载的更多相关文章

  1. vue-cli3 vue.config.js 配置

    // cli_api配置地址 https://cli.vuejs.org/zh/config/ module.exports = { baseUrl: './', // 部署应用包时的基本 URL o ...

  2. vuex 、store、state (转载)

    vuex  文档 https://vuex.vuejs.org/zh/guide/state.html

  3. vuex简介(转载)

    安装.使用 vuex 首先我们在 vue.js 2.0 开发环境中安装 vuex : npm install vuex --save 然后 , 在 main.js 中加入 : import vuex ...

  4. 前端 vue单页面应用刷新网页后vuex的state数据丢失的解决方案(转载)

    最近接手了一个项目,前端后端都要做,之前一直在做服务端的语言.框架和环境,前端啥都不会啊. 突然需要前端编程,两天速成了JS和VUE框架,可惜还是个半吊子.然后遇到了一个困扰了一整天的问题.一直调试都 ...

  5. Vuex源码解析

    写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:https://github.com/a ...

  6. 【前端】Vue2全家桶案例《看漫画》之三、引入vuex

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/vue_vux_app_3.html 项目github地址:https://github.com/shamoyuu/ ...

  7. Vue—组件传值及vuex的使用

    一.父子组件之间的传值 1.父组件向子组件传值: 子组件在props中创建一个属性,用以接收父组件传来的值 父组件中注册子组件 在子组件标签中添加子组件props中创建的属性 把需要传给子组件的值赋给 ...

  8. vue单页面应用刷新网页后vuex的state数据丢失的解决方案

    1. 产生原因其实很简单,因为store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里面的数据就会被重新赋值. 2. 解决思路一种是state里的数据全部是通过请求 ...

  9. 2、vuex页面刷新数据不保留,解决方法(转)

    今天这个问题又跟页面的刷新有一定的关系,虽然说跟页面刷新的关系不大,但确实页面刷新引起的这一个问题. 场景: VueX里存储了 this.$store.state.PV这样一个变量,这个变量是在app ...

随机推荐

  1. 10分钟彻底理解Redis的持久化机制:RDB和AOF

    作者:张君鸿 juejin.im/post/5d09a9ff51882577eb133aa9 什么是Redis持久化? Redis作为一个键值对内存数据库(NoSQL),数据都存储在内存当中,在处理客 ...

  2. Linux 磁盘分区、挂载

    一.分区介绍 mbr分区: 1.最多支持四个主分区 2.系统只能安装在主分区上 3.扩展分区要占一个主分区 4.mbr最大只支持2TB,但拥有最好的兼容性 gpt分区: 1.支持无限多个主分区(但操作 ...

  3. LeetCode刷题191120

    博主渣渣一枚,刷刷leetcode给自己瞅瞅,大神们由更好方法还望不吝赐教.题目及解法来自于力扣(LeetCode),传送门. 算法: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位 ...

  4. [20191101]通过zsh计算sql语句的sql_id.txt

    [20191101]通过zsh计算sql语句的sql_id.txt 1.简单介绍以及测试使用zsh遇到的问题:--//前段时间写的,链接http://blog.itpub.net/267265/vie ...

  5. MyBatis之接口绑定方案及多参数传递

    1.说明   所谓的MyBatis接口绑定,指的是实现创建一个接口后,把mapper.xml 由mybatis 生成接口的实现类,通过调用接口对象就可以获取mapper.xml 中编写的sql.在SS ...

  6. ramdisk配置、解压、创建rootfs、启动简单分析

    关键词:ramdisk.rdint..init.ramfs.__initramfs_start.__initramfs_size.rootfs.ramfs.populate_rootfs().gzip ...

  7. github.com/pkg/errors库学习

    为了理解go error,进一步学习github.com/pkg/errors作的训练. http://www.shtml.net/article/content/tok/48369/id/37733 ...

  8. 201871010102-常龙龙《面向对象程序设计(java)》第十六周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  9. git(1) 比较两个不同版本的文件

    git diff commit_id1:file_name commit_id2:file_name 或者 git diff commit_id1 commit_id2 -- file_name co ...

  10. 《icra16_slam_tutorial_tardos.pdf》

    icra16_slam_tutorial_tardos.pdf EKF: https://www.cnblogs.com/gaoxiang12/p/5560360.html 7. 小结 卡尔曼滤波是递 ...