关于vuex:vuex-全面解析看完即上手

7次阅读

共计 5016 个字符,预计需要花费 13 分钟才能阅读完成。

  • vuex 是采纳集中式治理组件依赖的共享数据的一个工具,能够解决不同组件数据共享问题。
  1. 批改 state 状态必须通过mutations
  2. mutations只能执行同步代码,相似 ajax,定时器之类的代码不能在 mutations 中执行
  3. 执行异步代码,要通过 actions,而后将数据提交给 mutations 才能够实现
  4. state 的状态即共享数据能够在组件中援用
  5. 组件中能够调用 action

vuex 根底 - 初始化性能

建设一个新的脚手架我的项目, 在我的项目中利用 vuex

$ vue create  demo

开始 vuex 的初始化建设,抉择模式时,抉择默认模式

初始化:

  • 第一步:npm i vuex --save => 装置到 运行时依赖 => 我的项目上线之后仍然应用的依赖 , 开发时依赖 => 开发调试时应用

开发时依赖 就是开开发的时候,须要的依赖,运行时依赖,我的项目上线运行时仍然须要的

  • 第二步:在 main.js 中 import Vuex from 'vuex'
  • 第三步:在 main.js 中 Vue.use(Vuex) => 调用了 vuex 中的 一个 install 办法
  • 第四步:const store = new Vuex.Store({... 配置项})
  • 第五步:在根实例配置 store 选项指向 store 实例对象
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)
const store = new Vuex.Store({})
new Vue({
  el: '#app',
  store
})

vuex 根底 -state

state 是搁置所有公共状态的属性,如果你有一个公共状态数据,你只须要定义在 state 对象中

定义 state

// 初始化 vuex 对象
const store = new Vuex.Store({
  state: {
    // 治理数据
    count: 0
  }
})

如何在组件中获取 count?

原始模式– 插值表达式

App.vue

组件中能够应用 this.$store 获取到 vuex 中的 store 对象实例,可通过 state 属性属性获取count,如下

<div> state 的数据:{{$store.state.count}}</div>

计算属性 – 将 state 属性定义在计算属性中

// 把 state 中数据,定义在组件内的计算属性中
  computed: {count () {return this.$store.state.count}
  }
 <div> state 的数据:{{count}}</div>

辅助函数 – mapState

mapState 是辅助函数,帮忙咱们把 store 中的数据映射到 组件的计算属性中, 它属于一种不便用法

用法:第一步:导入 mapState

import {mapState} from 'vuex'

第二步:采纳数组模式引入 state 属性

mapState(['count']) 

下面代码的最终失去的是 相似

count () {return this.$store.state.count}

第三步:利用 延展运算符 将导出的状态映射给计算属性

  computed: {...mapState(['count'])
  }
 <div> state 的数据:{{count}}</div>

vuex 根底 -mutations

state 数据的批改只能通过 mutations,并且 mutations 必须是同步更新

定义 mutations

const store  = new Vuex.Store({
  state: {count: 0},
  // 定义 mutations
  mutations: {}})

格局阐明

mutations 是一个对象,对象中寄存批改 state 的办法

mutations: {
    // 办法里参数 第一个参数是以后 store 的 state 属性
    // payload 载荷 运输参数 调用 mutaiions 的时候 能够传递参数 传递载荷
    addCount (state) {state.count += 1}
  },

如何在组件中调用 mutations

原始模式-$store

新建组件 child-a.vue,内容为一个 button 按钮,点击按钮调用 mutations

<template>
  <button @click="addCount">+1</button>
</template>

<script>
export default {
    methods: {
    //   调用办法
      addCount () {
         // 调用 store 中的 mutations 提交给 muations
        // commit('muations 名称', 2)
        this.$store.commit('addCount', 10)  // 间接调用 mutations
    }
  }
}
</script>

带参数的传递

    addCount (state, payload) {state.count += payload}
    this.$store.commit('addCount', 10)

辅助函数 – mapMutations

mapMutations 和 mapState 很像,它把位于 mutations 中的办法提取了进去,咱们能够将它导入

import  {mapMutations} from 'vuex'
methods: {...mapMutations(['addCount'])
}

下面代码的含意是将 mutations 的办法导入了 methods 中,等同于

methods: {// commit(办法名, 载荷参数)
      addCount () {this.$store.commit('addCount')
      }
 }

此时,就能够间接通过 this.addCount 调用了

<button @click="addCount(100)">+100</button>

然而请留神:Vuex 中 mutations 中要求不能写异步代码,如果有异步的 ajax 申请,应该搁置在 actions 中

vuex 根底 -actions

state 是存放数据的,mutations 是同步更新数据,actions 则负责进行异步操作

定义 actions

 actions: {
  //  获取异步的数据 context 示意以后的 store 的实例 能够通过 context.state 获取状态 也能够通过 context.commit 来提交 mutations,也能够 context.diapatch 调用其余的 action
    getAsyncCount (context) {setTimeout(function(){
        // 一秒钟之后 要给一个数 去批改 state
        context.commit('addCount', 123)
      }, 1000)
    }
 } 

原始调用 – $store

 addAsyncCount () {this.$store.dispatch('getAsyncCount')
 }

传参调用

 addAsyncCount () {this.$store.dispatch('getAsyncCount', 123)
 }

辅助函数 -mapActions

actions 也有辅助函数,能够将 action 导入到组件中

import {mapActions} from 'vuex'
methods: {...mapActions(['getAsyncCount'])
}

间接通过 this. 办法就能够调用

<button @click="getAsyncCount(111)">+ 异步 </button>

vuex 根底 -getters

除了 state 之外,有时咱们还须要从 state 中派生出一些状态,这些状态是依赖 state 的,此时会用到 getters

例如,state 中定义了 list,为 1 -10 的数组,

state: {list: [1,2,3,4,5,6,7,8,9,10]
}

组件中,须要显示所有大于 5 的数据,失常的形式,是须要 list 在组件中进行再一步的解决,然而 getters 能够帮忙咱们实现它

定义 getters

  getters: {
    // getters 函数的第一个参数是 state
    // 必须要有返回值
     filterList:  state =>  state.list.filter(item => item > 5)
  }

应用 getters

原始形式 -$store

<div>{{$store.getters.filterList}}</div>

辅助函数 – mapGetters

computed: {...mapGetters(['filterList'])
}
 <div>{{filterList}}</div>

Vuex 中的模块化 -Module

因为应用繁多状态树,利用的所有状态会集中到一个比拟大的对象。当利用变得非常复杂时,store 对象就有可能变得相当臃肿。

这句话的意思是,如果把所有的状态都放在 state 中,当我的项目变得越来越大的时候,Vuex 会变得越来越难以保护

由此,又有了 Vuex 的模块化

利用

定义两个模块 usersetting

user 中治理用户的状态 token

setting 中治理 利用的名称 name

const store  = new Vuex.Store({
  modules: {
    user: {
       state: {token: '12345'}
    },
    setting: {
      state: {name: 'Vuex 实例'}
    }
  })

定义 child- b 组件,别离显示用户的 token 和利用名称 name

<template>
  <div>
      <div> 用户 token {{$store.state.user.token}}</div>
      <div> 网站名称 {{$store.state.setting.name}}</div>
  </div>
</template>

请留神:此时要获取子模块的状态 须要通过 $store.state.模块名称 . 属性名 来获取

看着获取有点麻烦,咱们能够通过之前学过的 getters 来扭转一下

 getters: {
   token: state => state.user.token,
   name: state => state.setting.name
 } 

请留神:这个 getters 是根级别的 getters 哦

通过 mapGetters 援用

 computed: {...mapGetters(['token', 'name'])
 }

命名空间 namespaced

这里留神了解

默认状况下,模块外部的 action、mutation 和 getter 是注册在 全局命名空间 的——这样使得多个模块可能对同一 mutation 或 action 作出响应。

这句话的意思是 方才的 user 模块还是 setting 模块,它的 action、mutation 和 getter 其实并没有辨别,都能够间接通过全局的形式调用 如

  user: {
       state: {token: '12345'},
       mutations: {
        //  这里的 state 示意的是 user 的 state
         updateToken (state) {state.token = 678910}
       }
    },

通过 mapMutations 调用

 methods: {...mapMutations(['updateToken'])
  }
 <button @click="updateToken"> 批改 token</button>

然而,如果咱们想保障外部模块的高封闭性,咱们能够采纳 nameSpaced 来进行设置

高封闭性?能够了解成 一家人如果分家了,此时,你的爸妈能够随便的进出分给你的小家,你感觉本人没什么隐衷了,咱们能够给本人的房门加一道锁(命名空间 nameSpaced), 你的父母再也不能进出你的小家了

  user: {
       namespaced: true,
       state: {token: '12345'},
       mutations: {
        //  这里的 state 示意的是 user 的 state
         updateToken (state) {state.token = 678910}
       }
    },

应用带命名空间的模块 action/mutations/getters

计划 1:带上模块的属性名门路

  methods: {...mapMutations(['user/updateToken']),
       test () {this['user/updateToken']()}
   }
  <button @click="test"> 批改 token</button>

计划 2:createNamespacedHelpers 创立基于某个命名空间辅助函数

import {mapGetters, createNamespacedHelpers} from 'vuex'
const {mapMutations} = createNamespacedHelpers('user')
<button @click="updateToken"> 批改 token2</button>

正文完
 0