【博学谷学习记录】超强总结,用心分享|vuex

119 阅读2分钟

vuex概述

vuex 是一个 vue 的状态管理工具, 状态就是数据,可以帮助vue管理通用数据,在此之前,我们进行组件间数据通信,使用父传子,子传父的思想来实现,但当组件关系复杂时,数据将会非常难以维护,而vuex可以帮助我们轻松实现组件间的数据通信。

使用方法

一、基本使用

1.安装vuex,与vue-router类似,vuex是一个独立存在的插件,如果脚手架初始化没有选 vuex,就需要额外安装。 使用时注意版本,这里以vue2做演示

yarn add vuex@3.4.0

2.新建 store/index.js 专门存放vuex

3.store/index.js中创建仓库

// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)

// 创建仓库 store
const store = new Vuex.Store()

// 导出仓库
export default store

4.在main.js中导入挂载到Vue实例上

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store
}).$mount('#app')

到这就成功创建了一个空仓库

vuex中的核心概念

核心概念 - state 状态

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。

打开项目中的store.js文件,在state对象中可以添加我们要共享的数据。

// 创建仓库 store
const store = new Vuex.Store({
  // state 状态, 即数据, 类似于vue组件中的data,
  // 区别在于 data 是组件自己的数据, 而 state 中的数据整个vue项目的组件都能访问到
  state: {
    count: 101
  }
})

问题: 如何在组件中获取count?

  1. 插值表达式 =》 {{ $store.state.count }}
  2. mapState 映射计算属性 =》 {{ count }}

1 原始形式- 插值表达式

App.vue

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

<h1>state的数据 - {{ $store.state.count }}</h1>

计算属性 - 将state属性定义在计算属性中 vuex.vuejs.org/zh/guide/st…

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

但是每次, 都这样一个个的提供计算属性, 太麻烦了, 所以我们需要辅助函数 mapState 帮我们简化语法

2 辅助函数 - mapState

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

用法 :

第一步:导入mapState (mapState是vuex中的一个函数)

import { mapState } from 'vuex'

第二步:采用数组形式引入state属性

mapState(['count']) 

上面代码的最终得到的是 类似于

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

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

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

核心概念 - mutations

基本使用

通过 strict: true 可以开启严格模式

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

this.$store.commit('addCount')

解决问题: 两个子组件, 添加操作 add, addN 实现

带参数的 mutation

需求: 父组件也希望能改到数据

提交 mutation 是可以传递参数的 this.$store.commit('xxx', 参数)

1 提供mutation函数

mutations: {
  ...
  inputCount (state, count) {
    state.count = count
  }
},

2 注册事件

<input type="text" :value="count" @input="handleInput">

3 提交mutation

handleInput (e) {
  this.$store.commit('inputCount', +e.target.value)
}

小tips: 提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象

this.$store.commit('inputCount', {
  count: e.target.value
})

解决问题: addN 的实现

辅助函数 - 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">值+1</button>

但是请注意: Vuex中mutations中要求不能写异步代码,如果有异步的ajax请求,应该放置在actions中

核心概念-actions

state是存放数据的,mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化),

actions则负责进行异步操作

需求: 一秒钟之后, 要给一个数 去修改state

定义actions

actions: {
  setAsyncCount (context, num) {
    // 一秒后, 给一个数, 去修改 num
    setTimeout(() => {
      context.commit('inputCount', num)
    }, 1000)
  }
},

原始调用 - $store (支持传参)

setAsyncCount () {
  this.$store.dispatch('setAsyncCount', 200)
}

辅助函数 -mapActions

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

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

直接通过 this.方法 就可以调用

<button @click="setAsyncCount(200)">+异步</button>

核心概念-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>

核心概念 - 模块 module (进阶拓展)

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

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

由此,又有了Vuex的模块化

image.png

模块定义 - 准备 state

定义两个模块 usersetting

user中管理用户的信息状态 userInfo modules/user.js

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  }
}
​
const mutations = {}
​
const actions = {}
​
const getters = {}
​
export default {
  state,
  mutations,
  actions,
  getters
}
​

setting中管理项目应用的名称 title, desc modules/setting.js

const state = {
  title: '这是大标题',
  desc: '描述真呀真不错'
}
​
const mutations = {}
​
const actions = {}
​
const getters = {}
​
export default {
  state,
  mutations,
  actions,
  getters
}

使用模块中的数据, 可以直接通过模块名访问 $store.state.模块名.xxx => $store.state.setting.title

也可以通过 mapState 映射

命名空间 namespaced

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间

这句话的意思是 刚才的 user模块 还是 setting模块,它的 action、mutation 和 getter 其实并没有区分,都可以直接通过全局的方式调用, 如下图所示:

image.png

但是,如果我们想保证内部模块的高封闭性,我们可以采用namespaced来进行设置

modules/user.js

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  },
  myMsg: '我的数据'
}
​
const mutations = {
  updateMsg (state, msg) {
    state.myMsg = msg
  }
}
​
const actions = {}
​
const getters = {}
​
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

提交模块中的mutation

全局的:   this.$store.commit('mutation函数名', 参数)
​
模块中的: this.$store.commit('模块名/mutation函数名', 参数)

namespaced: true 后, 要添加映射, 可以加上模块名, 找对应模块的 state/mutations/actions/getters

computed: {
  // 全局的
  ...mapState(['count']),
  // 模块中的
  ...mapState('user', ['myMsg']),
},
methods: {
  // 全局的
  ...mapMutations(['addCount'])
  // 模块中的
  ...mapMutations('user', ['updateMsg'])
}