当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Vuex基本使用的总结--转载

Vuex基本使用的总结--转载

2019年11月26日  | 移动技术网IT编程  | 我要评论

在 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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网