VUE-Store

VUE-Store

引言

Store(仓库)的概念引向于VUEX的应用中,store基本上就是一个容器,它包含着你的应用中大部分的状态。vue的状态存储是响应式的,当vue组件从store中读取状态的时候,若store的状态发生变化,那么相应的组件也会相应的高效更新。并且不能直接的改变store中的状态,改变store中的状态的唯一途径就是显式的提交,这样使得我们可以方便的追踪每一个状态的变化。

我们通过官方文档的一个小例子,来熟悉一个store的使用。

一开始我们先利用webpack来构建一个vue的基本项目,

image-20201127143429229

store是基于vuex的核心概念,首先需要安装vuex,这里我直接在终端输入npm install vuex --save ,即安装完成,

在目录上创建store文件,为了保存项目结构的规整,在之下创建store.js文件,导入相关的语句:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

于此同时,在main.js进行注册。

我们继续完善这个小栗子:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 创建一个store
export default new Vuex.Store({
    // 设置全局访问的state对象
    state: {
        count: 25,
    },
    // 修改状态
    mutations: {
        increment(state) {
            state.count++
        }
    }
})

在组件中直接获取值,感受一下:

<template>
  <div>
    <h1>{{this.$store.state.count}}</h1>
    <button @click="increment">点击我!</button>
  </div>
</template>

<script>
    export default {
        name: "main",
        methods:{
          increment(){
            this.$store.commit('increment')
            console.log(this.$store.state.count)
          }
        }
    }
</script>

<style scoped>

</style>

image-20201127144204736

参考官方的例子,这个简单的计数器被实现了。不过到这里,感觉类似于全局变量。接着往下看。

相关概念

state

vuex使用的单一状态树,即一个对象包含了全部的应用层级,每个应用将仅仅包含一个store实例,单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

从store实例中读取状态

// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

每当store.state.count变化的时候,都会重新求取计算属性,并且触发更新相关联的DOM。

Vuex通过store选项,提供了一种机制将状态从根组件注入到每一个子组件中。通过store选项,提供了一种机制将状态从跟组件注入到每一个子组件,可以通过this.$store.state.count获取到。

mapState辅助函数

当一个需要获取多个状态时候,将这些状态都声明为计算属性会繁杂,vuex中提供了mapState来帮我们。我们改变一下上述的例子

<template>
  <div>
    <h1>{{this.$store.state.count}}</h1>
    <button @click="increment">点击我!</button>
    <h1>我在这{{count}}</h1>
    <h1>我在这{{count1}}</h1>
    <h1>我在这{{LocalState}}</h1>
  </div>
</template>

<script>
    import {mapState} from 'vuex';
    export default {
        name: "main",
        data: function(){
          return {
            LocalCount:8,
          }
        },
        computed: mapState({
          count:state => state.count,
          count1 :'count',
          LocalState(state){
            return state.count +this.LocalCount
          }
        }),
        methods:{
          increment(){
            this.$store.commit('increment')
            console.log(this.$store.state.count)
          }
        }
    }
</script>

<style scoped>

</style>

结果:

image-20201127150822488

getter

我们需要从state中派生出一些状态属性,这个时候就可以选择使用getter。

废话不说,直接上例子,就会明白:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    // 设置全局访问的state对象
    state: {
        todos: [
            { id: 1, text: '...', done: true },
            { id: 2, text: '...', done: false },
            { id: 3, text: '...', done: true },
            { id: 4, text: '...', done: true },
            { id: 5, text: '...', done: true },
            { id: 6, text: '...', done: true },
            { id: 7, text: '...', done: true },
            { id: 8, text: '...', done: true },
        ]
    },
    getters: {
        doneTodos: state => {
            // 获取列表中done属性为true的
            return state.todos.filter(todo => todo.done)
        }
    }
})

组件中使用:

<template>
  <div>
    <h1>{{this.$store.state.count}}</h1>
    <button @click="increment">点击我!</button>
    <h1>我在getter--->{{doneTodosCount}}</h1>
    
  </div>
</template>

<script>
    import {mapState} from 'vuex';
    export default {
        name: "main",
        data: function(){
          return {
            LocalCount:8,
          }
        },
        computed:{
          doneTodosCount () {
              return this.$store.state.todos.filter(todo => todo.done).length
            }
        },
        methods:{
          increment(){
            this.$store.commit('increment')
            console.log(this.$store.state.count)
          }
        }
    }
</script>

<style scoped>

</style>

也通过属性访问。通过this.getters.donTodos就可以。

Mutation

这个概念,我们在第一个例子中就已经进行使用了,

直接按照官方文档的说法:

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,

直接调用以相应的 type 调用 store.commit 方法:

action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

让我们来注册一个简单的 action:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

实践中,我们会经常用到 ES2015 的 参数解构 (opens new window)来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

分发 Action

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

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

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

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

来看一个更加实际的购物车示例,涉及到调用异步 API分发多重 mutation

actions: {
  checkout ({ commit, state }, products) {
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求,然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)。

在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

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

组合 Action

Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

现在你可以:

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

在另外一个 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最后,如果我们利用 async / await (opens new window),我们可以如下组合 action:

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

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

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

参考资料

VUEX官方文档

  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值