vue2/3学习(7)

127 阅读2分钟

vuex

  1. vuex是什么:
  • vuex 是一个 vue 的 状态管理工具,状态就是数据。
  • vuex 是一个插件,可以帮我们管理 vue 通用的数据 (多组件共享的数据)
  1. 场景:
  • 某个状态 在 很多个组件 来使用 (个人信息)
  • 多个组件 共同维护 一份数据 (购物车)
  1. 优势:
  • 共同维护一份数据,数据集中化管理
  • 响应式变化
  • 操作简洁 (vuex提供了一些辅助函数)

构建多组件共享的数据环境

屏幕截图 2024-01-30 130414.png 1.创建项目

//shft + 鼠标右键 → 在此处打开Powershell窗口,输入
vue create vuex-demo

2.创建三个组件, 目录如下

components
Son1.vue
Son2.vue
App.vue

3.代码如下

App.vue在入口组件中引入 Son1 和 Son2 这两个子组件

<template>
  <div id="app">
    <h1>根组件</h1>
    <input type="text">
    <Son1></Son1>
    <hr>
    <Son2></Son2>
  </div>
</template>

<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'

export default {
  name: 'app',
  data: function () {
    return {

    }
  },
  components: {
    Son1,
    Son2
  }
}
</script>

<style>
#app {
  width: 600px;
  margin: 20px auto;
  border: 3px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}
</style>

main.js

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

Vue.config.productionTip = false

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

Son1.vue

<template>
  <div class="box">
    <h2>Son1 子组件</h2>
    从vuex中获取的值: <label></label>
    <br>
    <button>值 + 1</button>
  </div>
</template>

<script>
export default {
  name: 'Son1Com'
}
</script>

<style lang="css" scoped>
.box{
  border: 3px solid #ccc;
  width: 400px;
  padding: 10px;
  margin: 20px;
}
h2 {
  margin-top: 10px;
}
</style>

Son2.vue

<template>
  <div class="box">
    <h2>Son2 子组件</h2>
    从vuex中获取的值:<label></label>
    <br />
    <button>值 - 1</button>
  </div>
</template>

<script>
export default {
  name: 'Son2Com'
}
</script>

<style lang="css" scoped>
.box {
  border: 3px solid #ccc;
  width: 400px;
  padding: 10px;
  margin: 20px;
}
h2 {
  margin-top: 10px;
}
</style>

image.png

核心概念 - state状态

1. 提供数据:

  • state 提供唯一的公共数据源,所有共享的数据都要统一放到 store 中的 state 中存储。
  • 在 state 对象中可以添加我们要共享的数据。
// 创建仓库
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data
// 区别:
// 1. data 是组件自己的数据
// 2. state 是所有组件共享的数据
state: {
count: 101
}
})

2. 使用数据:

  • 通过 store 直接访问
  • 通过辅助函数
获取 store:
(1) this.$store
(2) import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx

核心概念 - mutations

vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据,state数据的修改只能通过mutations

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

const store = new Vuex.Store({
    state: {
        count: 0
    },
// 定义mutations
    mutations: {
// 第一个参数是当前store的state属性
        addCount (state) {
            state.count += 1
        }
    }
})

2. 组件中提交调用 mutations

this.$store.commit('addCount')

3.辅助函数 - mapMutations

mutations: {
    subCount (state, n) {
        state.count -= n
    },
}
import { mapMutations } from 'vuex'
    methods: {
    ...mapMutations(['subCount'])
}
 
methods: {
    subCount (n) {
        this.$store.commit('subCount', n)
    },
}

核心概念 - actions

actions处理异步,不能直接操作state,操作state需要 commit mutation

  1. 提供 action 方法
actions: {
    setAsyncCount (context, num) {
        // 一秒后, 给一个数, 去修改 num
        setTimeout(() => {
            context.commit('changeCount', num)
        }, 1000)
    }
}
  1. 页面中 dispatch 调用
setAsyncCount () { 
this.$store.dispatch('setAsyncCount', 666) 
}

辅助函数:mapActions

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

import { mapState,mapMutations,mapActions  } from 'vuex'

methods:{
    ...mapActions (['仓库中对应的actions函数名'])
}
  • 使用时直接使用仓库中对应的函数名就行

相当于在methods自动添加的了一个函数:

methods:{
    仓库中对应的actions函数名 (参数){
        this.$store.dispatch('action 名字',参数)
    }
}

核心概念 - getters

  1. 定义 getters
getters: {
// 注意:
//1. getters函数的第一个参数是 state
//2. getters函数必须要有返回值
    filterList (state) {
        return state.list.filter(item => item > 5)
    }
}
  1. 访问 getters
  • 通过 store 访问 getters

    {{ $store.getters.函数名}}
    
  • 通过辅助函数 mapGetters映射

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

核心概念-模块module(进阶语法)

由于vuex使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。(当项目变得越来越大的时候,Vuex会变得越来越难以维护)

//模块拆分:
const state = {
    userInfo: {
    name: 'zs',
    age: 18
}
}
const mutations = {}
const actions = {}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}

user模块: store/modules/user.js

使用模块中的数据:

  1. 直接通过模块名访问

    $store.state.模块名.xxx
    
  2. 通过 mapState 映射

    • 需要开启命名空间

      export default{
          namespace:true,
          
          state,
          mutations,
          actions,
          getters
      }
      
      mapState('模块名',['xxx'])
      

使用模块中的 getters 中的数据:

  1. 直接通过模块名访问

    $store.getters['模块名/xxx']
    
  2. 通过 mapGetters 映射

  • 默认根级别的映射 mapGetters([ 'xxx' ])

  • 子模块的映射 mapGetters('模块名', ['xxx']) —— 需要开启命名空间

    computed: {
        ...mapGetters('模块名',['xxx'])
    }
    

模块中mutation的调用语法:

注意:默认模块中的mutationactions会被挂载到全局

需要开启命名空间,才会挂载到子模块

  1. 直接通过 store 调用

    $store.commit('模块名/xxx',额外参数)
    
  2. 通过 mapMutations 映射 子模块的映射 (需要开启命名空间)

    methods {
       ... mapMutations('模块名',['xxx'])
    }
    

模块中 action 的调用语法:

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

调用语法:

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