vuex仓库的五大属性、辅助函数与使用方法,史上最详细!

简介: vuex仓库的五大属性、辅助函数与使用方法,史上最详细!

一、核心属性 - state 状态

1.目标

明确如何给仓库 提供 数据,如何 使用 仓库的数据

2.提供数据

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

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

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

3.访问Vuex中的数据

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

  1. 通过$store直接访问 —> {{ $store.state.count }}
  2. 通过辅助函数mapState 映射计算属性 —> {{ count }}

4.通过$store访问的语法

 

 获取 store:

  1.Vue模板中获取 this.$store

  2.js文件中获取 import 导入 store

 

 

 模板中:     {{ $store.state.xxx }}

 组件逻辑中:  this.$store.state.xxx

 JS模块中:   store.state.xxx

5.代码实现

5.1模板中使用

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

 

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

5.2组件逻辑中使用

将state属性定义在计算属性中 State | Vuex

 <h1>state的数据 - {{ count }}</h1>
 
  // 把state中数据,定义在组件内的计算属性中
    computed: {
      count () {
        return this.$store.state.count
      }
    }
5.3 js文件中使用
 
  //main.js
  
  import store from "@/store"
  
  console.log(store.state.count)

每次都像这样一个个的提供计算属性, 太麻烦了,我们有没有简单的语法帮我们获取state中的值呢?接着往下看

二、通过辅助函数 - mapState获取 state中的数据

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

用法 :

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

 

 import { mapState } from 'vuex'

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

 

 mapState(['count'])

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

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

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

 

   computed: {

     ...mapState(['count'])

   }  


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

三、开启严格模式及Vuex的单项数据流

1.目标

明确 vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据

2.直接在组件中修改Vuex中state的值

Son1.vue

button @click="handleAdd">值 + 1</button>
  methods:{
     handleAdd (n) {
        // 错误代码(vue默认不会监测,监测需要成本)
         this.$store.state.count++
        // console.log(this.$store.state.count) 
      },
  }

3.开启严格模式

通过 strict: true 可以开启严格模式,开启严格模式后,直接修改state中的值会报错

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

四、核心属性-mutations

1.定义mutations

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

2.格式说明

mutations是一个对象,对象中存放修改state的方法

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

3.组件中提交 mutations

 

 this.$store.commit('addCount')

4.总结

通过mutations修改state的步骤

1.定义 mutations 对象,对象中存放修改 state 的方法

2.组件中提交调用 mutations(通过$store.commit('mutations的方法名'))

五、带参数的 mutations

1.目标:

掌握 mutations 传参语法

2.语法

看下面这个案例,每次点击不同的按钮,加的值都不同,每次都要定义不同的mutations处理吗?

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

2.1 提供mutation函数(带参数)

 

 mutations: {

   ...

   addCount (state, count) {

     state.count = count

   }

 },

2.2 提交mutation

 

 handle ( ) {

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

 }

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

 

 this.$store.commit('addCount', {

   count: 10

 })

六、练习-mutations的减法功能

小练习:实现三种不同的减值效果,效果图如下:

1.步骤

2.代码实现

Son2.vue

  
      <button @click="subCount(1)">值 - 1</button>
      <button @click="subCount(5)">值 - 5</button>
      <button @click="subCount(10)">值 - 10</button>
  
      export default {
          methods:{
               subCount (n) { 
                  this.$store.commit('addCount', n)
          },
          }
      }

store/index.js

  
  mutations:{
      subCount (state, n) {
        state.count -= n
      },
  }

七、练习-Vuex中的值和组件中的input双向绑定

1.目标

实时输入,实时更新,巩固 mutations 传参语法

2.实现步骤

3.代码实现

App.vue

  
  <input :value="count" @input="handleInput" type="text">
  export default {
    methods: {
      handleInput (e) {
        // 1. 实时获取输入框的值
        const num = +e.target.value
        // 2. 提交mutation,调用mutation函数
        this.$store.commit('changeCount', num)
      }
    }
  }

store/index.js

  mutations: { 
     changeCount (state, newCount) {
        state.count = newCount
     }
  },

八、辅助函数- 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则负责进行异步操作

说明:mutations必须是同步的

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

1.定义actions

  
  mutations: {
    changeCount (state, newCount) {
      state.count = newCount
    }
  }


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

2.组件中通过dispatch调用

 

 setAsyncCount () {

   this.$store.dispatch('setAsyncCount', 666)

 }

十、辅助函数 -mapActions

1.目标

掌握辅助函数 mapActions,映射方法

mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中

Son2.vue

  import { mapActions } from 'vuex'
  methods: {
     ...mapActions(['changeCountAction'])
  }
  
  //mapActions映射的代码 本质上是以下代码的写法
  //methods: {
  //  changeCountAction (n) {
  //    this.$store.dispatch('changeCountAction', n)
  //  },
  //}

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

 

 <button @click="changeCountAction(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可以帮助我们实现它

1.定义getters

 

   getters: {

     // getters函数的第一个参数是 state

     // 必须要有返回值

      filterList:  state =>  state.list.filter(item => item > 5)

   }

2.使用getters

2.1原始方式-$store

 

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

2.2辅助函数 - mapGetters

 

 computed: {

     ...mapGetters(['filterList'])

 }

 

  <div>{{ filterList }}</div>

十二、使用小结

十三、核心属性 - module

1.目标

掌握核心概念 module 模块的创建

2.问题

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

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

由此,又有了Vuex的模块化

3.模块定义 - 准备 state

定义两个模块 usersetting

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

setting中管理项目应用的 主题色 theme,描述 desc, modules/setting.js

  
  const state = {
    theme: 'dark'
    desc: '描述真呀真不错'
  }
  
  const mutations = {}
  
  const actions = {}
  
  const getters = {}
  
  export default {
    state,
    mutations,
    actions,
    getters
  }

store/index.js文件中的modules配置项中,注册这两个模块

  import user from './modules/user'
  import setting from './modules/setting'
  
  const store = new Vuex.Store({
      modules:{
          user,
          setting
      }
  })

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

也可以通过 mapState 映射

十四、获取模块内的state数据

1.目标:

掌握模块中 state 的访问语法

尽管已经分模块了,但其实子模块的状态,还是会挂到根级别的 state 中,属性名就是模块名

2.使用模块中的数据

  1. 直接通过模块名访问 $store.state.模块名.xxx
  2. 通过 mapState 映射:
  1. 默认根级别的映射 mapState([ 'xxx' ])
  2. 子模块的映射 :mapState('模块名', ['xxx']) - 需要开启命名空间 namespaced:true

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
  }

3.代码示例

$store直接访问

 

 $store.state.user.userInfo.name

mapState辅助函数访问

 

 ...mapState('user', ['userInfo']),

 ...mapState('setting', ['theme', 'desc']),

十五、获取模块内的getters数据

1.目标:

掌握模块中 getters 的访问语

2.语法:

使用模块中 getters 中的数据:

  1. 直接通过模块名访问 $store.getters['模块名/xxx ']
  2. 通过 mapGetters 映射
  1. 默认根级别的映射 mapGetters([ 'xxx' ])
  2. 子模块的映射 mapGetters('模块名', ['xxx']) - 需要开启命名空间

3.代码演示

modules/user.js

const getters = {
    // 分模块后,state指代子模块的state
    UpperCaseName (state) {
      return state.userInfo.name.toUpperCase()
    }
  }

Son1.vue 直接访问getters

  
  <!-- 测试访问模块中的getters - 原生 -->
  <div>{{ $store.getters['user/UpperCaseName'] }}</div>

Son2.vue 通过命名空间访问

 computed:{
    ...mapGetters('user', ['UpperCaseName'])
  }

十六、获取模块内的mutations方法

1.目标:

掌握模块中 mutation 的调用语法

2.注意:

默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。

3.调用方式:

  1. 直接通过 store 调用 $store.commit('模块名/xxx ', 额外参数)
  2. 通过 mapMutations 映射
  1. 默认根级别的映射 mapMutations([ 'xxx' ])
  2. 子模块的映射 mapMutations('模块名', ['xxx']) - 需要开启命名空间

4.代码实现

modules/user.js

 

 const mutations = {

   setUser (state, newUserInfo) {

     state.userInfo = newUserInfo

   }

 }

modules/setting.js

 

 const mutations = {

   setTheme (state, newTheme) {

     state.theme = newTheme

   }

 }

Son1.vue

  
  <button @click="updateUser">更新个人信息</button> 
  <button @click="updateTheme">更新主题色</button>

  export default {
    methods: {
      updateUser () {
        // $store.commit('模块名/mutation名', 额外传参)
        this.$store.commit('user/setUser', {
          name: 'xiaowang',
          age: 25
        })
      }, 
      updateTheme () {
        this.$store.commit('setting/setTheme', 'pink')
      }
    }
  }

Son2.vue

 <button @click="setUser({ name: 'xiaoli', age: 80 })">更新个人信息</button>
  <button @click="setTheme('skyblue')">更新主题</button>
  
  methods:{
  // 分模块的映射
  ...mapMutations('setting', ['setTheme']),
  ...mapMutations('user', ['setUser']),
  }

十七、获取模块内的actions方法

1.目标:

掌握模块中 action 的调用语法 (同理 - 直接类比 mutation 即可)

2.注意:

默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。

3.调用语法:

  1. 直接通过 store 调用 $store.dispatch('模块名/xxx ', 额外参数)
  2. 通过 mapActions 映射
  1. 默认根级别的映射 mapActions([ 'xxx' ])
  2. 子模块的映射 mapActions('模块名', ['xxx']) - 需要开启命名空间

4.代码实现

需求:

modules/user.js

 
  const actions = {
    setUserSecond (context, newUserInfo) {
      // 将异步在action中进行封装
      setTimeout(() => {
        // 调用mutation   context上下文,默认提交的就是自己模块的action和mutation
        context.commit('setUser', newUserInfo)
      }, 1000)
    }
  }

Son1.vue  直接通过store调用

 
  <button @click="updateUser2">一秒后更新信息</button>
  
  methods:{
      updateUser2 () {
        // 调用action dispatch
        this.$store.dispatch('user/setUserSecond', {
          name: 'xiaohong',
          age: 28
        })
      },
  }

Son2.vue  mapActions映射

  <button @click="setUserSecond({ name: 'xiaoli', age: 80 })">一秒后更新信息</button>
  
  methods:{
    ...mapActions('user', ['setUserSecond'])
  }

十八、Vuex模块化的使用小结

1.直接使用

  1. state --> $store.state.模块名.数据项名
  2. getters --> $store.getters['模块名/属性名']
  3. mutations --> $store.commit('模块名/方法名', 其他参数)
  4. actions --> $store.dispatch('模块名/方法名', 其他参数)

2.借助辅助方法使用

1.import { mapXxxx, mapXxx } from 'vuex'

computed、methods: {

// ...mapState、...mapGetters放computed中;

// ...mapMutations、...mapActions放methods中;

...mapXxxx('模块名', ['数据项|方法']),

...mapXxxx('模块名', { 新的名字: 原来的名字 }),

}

2.组件中直接使用 属性 {{ age }}方法 @click="updateAge(2)"


相关文章
|
11天前
|
JavaScript 前端开发
Vue组件生命周期深度剖析:从创建到销毁的八大钩子实战指南
Vue组件生命周期深度剖析:从创建到销毁的八大钩子实战指南
|
2月前
|
JavaScript Java 测试技术
基于小程序的外卖点餐+springboot+vue.js附带文章和源代码设计说明文档ppt
基于小程序的外卖点餐+springboot+vue.js附带文章和源代码设计说明文档ppt
25 2
|
2月前
|
JavaScript Java 测试技术
基于ssm+vue.js的幼儿资源互助共享平台附带文章和源代码设计说明文档ppt
基于ssm+vue.js的幼儿资源互助共享平台附带文章和源代码设计说明文档ppt
17 0
|
2月前
|
存储 JSON JavaScript
vue整合kitymind百度脑图-引用打包文件方案
vue整合kitymind百度脑图-引用打包文件方案
49 0
|
9月前
|
JavaScript
Vue3 Reactive及其衍生函数 源码探析
Vue3 Reactive及其衍生函数 源码探析
|
11月前
|
缓存 JavaScript 程序员
[Vue项目实战]尚品汇 -- 初始化项目以及项目的配置与分析
[Vue项目实战]尚品汇 -- 初始化项目以及项目的配置与分析
[Vue项目实战]尚品汇 -- 初始化项目以及项目的配置与分析
|
存储 资源调度 前端开发
搭建Vue3组件库:第十二章 使用 Monorepo 方式管理组件生态
本章介绍采用Monorepo的方式管理组件生态
935 0
搭建Vue3组件库:第十二章 使用 Monorepo 方式管理组件生态
|
存储
学习Pinia 第二章(初始化仓库Store)
这个名称,也称为id,是必要的,Pania 使用它来将商店连接到 devtools。将返回的函数命名为use...是可组合项之间的约定,以使其使用习惯。
130 0
|
前端开发 JavaScript Unix
搭建Vue3组件库:第十章 开源许可证
本章介绍一下开源许可证。
424 0
搭建Vue3组件库:第十章 开源许可证
|
JavaScript 前端开发 开发者
拓展-Vue 中实例的生命周期1(2)|学习笔记
快速学习拓展-Vue 中实例的生命周期1(2)
65 0
拓展-Vue 中实例的生命周期1(2)|学习笔记