VUE2,VUE3中Vuex的使用详解

发布于:2023-01-20 ⋅ 阅读:(477) ⋅ 点赞:(0)

文章目录 

一、Vuex是什么

 Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

优点:

能够在Vuex中集中管理共享的数居,易于开发和后期维护
能够高效地实现组件之间的数据共享,提高开发效率
存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中:

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。

1.1 安装与使用

vue2:

main.js

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

Vue.config.productionTip = false

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

store / index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

vue3:

store/index.js

 

main.js

 

 1.2 store和单纯的全局对象有什么区别?

  1. store中的数据是响应式的当,Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新;
  2. 不能直接修改store中的数据,只能通过提交commit来修改,这样使得我们可以方便的跟踪每一个状态的变化,从而让我们能够通过一些工具帮助我们更好的管理应用的状态

二、State 数据源

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

2.1 通过 this.$store.state.全局数据名称 访问

this.$store.state.全局数据名称

由于在模板字符串中,是不需要写this的,所以直接写this后边的。

<h3>当前最新的count值为:{{$store.state.count}}</h3>

直接写this.$store.state.name 过于繁琐,可以在计算属性里面返回,然后直接使用计算属性的值:

computed: {
      name() {
        return this.$store.state.name
      }
}

 vue3的composition api中使用 :

import { mapState, useStore } from 'vuex'
import { computed } from 'vue'

  export default {
    setup() {
      const store = useStore()
      const sCounter = computed(() => store.state.counter)
      return {
        sCounter
      }
    }
  }

2.2 mapState 映射为计算属性

通过导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed计算属性:

mapState()接受数组或者对象作为参数:

vue2的options中使用:

<!-- 使用: -->
<h3>当前最新的count值为:{{ count }}</h3>
//1.导入辅助函数 mapState
import { mapState } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
  	// 将count映射为计算属性
    ...mapState(['count']),
    // 将sCounter,sName映射为计算属性
    ...mapState({
        sCounter: state => state.counter,
        sName: state => state.name
      })
  },
}

vue3的composition api中使用 

在setup()中使用mapState()得到的返回值无法直接使用,必须经过一层封装

  • 这是因为通过mapState()得到的getter函数内部是通过this.$store去获取状态,但是getter函数中的this并没有绑定到vue实例,直接执行的函数中this指向windows,所以读取this.$store会报错,需要手动将函数的this绑定到{$store:store}
  • 通过mapState()解析得到的数据只是普通函数,不是响应式的,需要用computed()包裹
import { mapState, useStore } from 'vuex'
import { computed } from 'vue'
  export default {
    setup() {
      const store = useStore()
      const storeStateFns = mapState(["counter", "name", "age", "height"])
      const storeState = {}
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
      })
      return {
        ...storeState
      }
    }
  }

mapState()的返回值是一个对象,对象中的每一个值对应一个getter函数

storeStateFns = {
        function counter (){
          return this.$store.state.conter
          },
        function name (){
            return this.$store.state.name
          }
     }

 

三、Mutations 变更store中的数据

注意: 只有 mutations里的函数,才有权利修改 state 的数据
注意: mutations里不能包含异步操作

①只能通过 mutations变更 Store数据,不可以直接操作 Store中的数据。
②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化

const store = new Vuex.Store({
  state:{
	count:0
  },
  mutations:{
	add(state){
	  //变更状态
	  state.count++
	}
  }
})

3.1 this.$store.commit() 触发 mutations

this.$store.commit() 是触发 mutations的第一种方式 

Increment() {
  this.$store.commit('add')
},

 3.1.1 触发 mutations 时传递值

IncrementN(){
  this.$store.commit('addN',{num:5})
}

mutations: {
  add(state) {
    // 变更状态
    state.count++
  },
  addN(state,step){
    // 变更状态
    state.count += step.num
  }
},

3.2 MapMutations 映射为方法

options api:

1.从vuex中按需导入 mapMutations函数
import {mapMutations} from 'vuex'

2.通过按需导入的 mapMutations函数,映射为当前组件的methods函数。

// store
mutations: {
  add(state) {
    // 变更状态
    state.count++
  },
  sub(state) {
    state.count--
  },
  addN(state, step) {
    // 变更状态
    state.count += step
  },
  subN(state, step) {
    state.count -= step
  }
},

// 组件A
import { mapState,mapMutations } from 'vuex'
methods:{
// 在methods中注册sub,subN方法
  ...mapMutations(['sub','subN']),
  decrement(){
    // 调用 
    this.sub()
  },
  decrementN(){
    this.subN(5)
  }
}

compotions api:

 import { mapMutations, mapState } from 'vuex'

  export default {
    methods: {
      ...mapMutations(["increment", "decrement"]),
      ...mapMutations({
        add: "increment"
      })
    },
    setup() {
      const storeMutations = mapMutations(["increment", "decrement"])

      return {
        ...storeMutations
      }
    }
  }

3.3 Mutation常量类型

 当我们的项目增大时, Vuex管理的状态越来越多, 需要更新状态的情况越来越多, 那么意味着Mutation中的方法越来越多. 方法过多, 使用者需要花费大量的经历去记住这些方法, 可能还会出现写错的情况.

  • 我们可以创建一个文件: mutation-types.js, 并且在其中定义我们的常量.
  • 定义常量时, 我们可以使用ES2015中的风格, 使用一个常量来作为函数的名称.

 

3.4 Mutation同步函数

  Vuex要求我们Mutation中的方法必须是同步方法.

  • 主要的原因是当我们使用devtools时, 可以devtools可以帮助我们捕捉mutation的快照.
  • 但是如果是异步操作, 那么devtools将不能很好的追踪这个操作什么时候会被完成.

四、Actions 专门处理异步操作

如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。

注意: 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。

action的参数context?

context是和store对象具有相同方法和属性的对象,可以通过context去进行commit相关的操作, 也可以获取context.state等.

但是注意, 这里它们并不是同一个对象, 为什么呢? 我们后面学习Modules的时候, 再具体说.

4.1 this.$store.dispatch 触发 Actions

store.js

// 定义 Action
const store = new Vuex.store({
  // ...省略其他代码
  mutations: {
    // 只有 mutations中的函数才有权利修改 state。
    // 不能在 mutations里执行异步操作。
    add(state,payload) {
      state.count+=payload
    }
  },
  actions: {
    // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
    // 也可以接受payload
    addAsync(context,payload) {
      setTimeout(() => {
        context.commit('add',payload)
      }, 1000);
    }
  },
})

组件A

// 触发 Action
methods:{
  handle(){
    // 触发 actions 的第一种方式
    this.$store.dispatch('addAsync',5)
  }
}

4.2 mapActions 映射为方法

options api:

1.从Vuex中按需导入 mapActions 函数。

import {mapActions} from 'vuex'

2.将指定的 actions 函数,映射为当前组件 methods 的方法。

methods:{
  ...mapActions(['subAsync']),
  decrementAsync(){
    this.subAsync()
  }
}

 store.js

actions: {
 // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
  subAsync(context){
    setTimeout(() => {
      context.commit('sub')
    }, 1000);
  }
}

compotion  api:

 import { mapActions } from 'vuex'

  export default {
    methods: {
      ...mapActions(["incrementAction", "decrementAction"]),
      ...mapActions({
        add: "incrementAction",
        sub: "decrementAction"
      })
    },
    setup() {
      const actions = mapActions(["incrementAction", "decrementAction"])
      const actions2 = mapActions({
        add: "incrementAction",
        sub: "decrementAction"
      })

      return {
        ...actions,
        ...actions2
      }
    }
  }

五、Getter

  • Getter 用于对 Store中的数据进行加工处理形成新的数据。
  • Getter 不会修改 Store 中的原数据,它只起到一个包装器的作用,将Store中的数据加工后输出出来。
  • Getter可以对 Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
  • Store中数据发生变化, Getter 的数据也会跟着变化。
  • getter第一个参数是state,第二个参数是getters
//定义 Getter
const store = new Vuex.Store({
  state:{
	count:0,
    name: ''
  },
  getters: {
    showNum(state) {
      return '当前最新的数量是【' + state.count + '】'
    },
    showNameNum(state,getters){
        return state.name + getters.shouNum
    }
  },
})

getters默认是不能传递参数的, 如果希望传递参数, 那么只能让getters本身返回另一个函数

//定义 Getter
const store = new Vuex.Store({
  state:{
	count:0,
    name: ''
  },
  getters: {
    getLenById(state) {
      return (id)=>{return id.length}
    }
  },
})
//组件中使用
this.$store.getters.getLenById(1)

5.1 通过 this.$store.getters.名称 访问

this.$store.getters.名称

5.2 mapGetters 映射为计算属性

options api:

 

 composition api:封装一个Hooks

 

6.modules

 Vuex允许我们将store分割成模块(Module), 而每个模块拥有自己的state、mutation、action、getters等

定义一个homeModule:

// homeModule
const homeModule = {
  namespaced: true,
  state() {
    return {
      homeCounter: 100
    }
  },
  getters: {
    doubleHomeCounter(state, getters, rootState, rootGetters) {
      return state.homeCounter * 2
    },
    otherGetter(state) {
      return 100
    }
  },
  mutations: {
    increment(state,rootState) {
      state.homeCounter++
      rootState.age++
    }
  },
  actions: {
// 参数中没有rootCommit,rootDispatch
    incrementAction({commit, dispatch, state, rootState, getters, rootGetters}) {
      commit("increment")
    // module中调用根方法,或者根action
      commit("increment", null, {root: true})
      dispatch('getData',null,{toor:true})
    }
  }
}
export default homeModule

模块注意事项:

  • mutations,getters,actions中的参数添加了对应的根目录中的数据
  • 如果在定义模块时,没有定义namespaced,则namespaced默认为false,此时state,mutations,getters,actions还是注册在全局命名空间,在组件中使用和以前一样
  • namespaced:true,模块会有自己的命名空间,在组件中使用模块中的内容是需要加上模块

在组件中使用:

直接使用:
this.$store.state.home.homeCounter
this.$store.getter.home.homeCounter
this.$store.commit("home/increment")
this.$store.dispatch("home/incrementAction")

辅助函数:

mapState(mapGetters类型)

import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({  
    // 参数为对象
    count: state => state.count, // 箭头函数可使代码更简练 映射为this.count
    userCount: state => state => state.user.count, // 模块化写法 映射为this.userCount
  })
    ...mapState('user',{count:'count',userCount:'userCount'})
     // 参数为数组
    ... mapState('user', ['count', 'name'])
    }
}

mapMutations(mapAction类似)

import { mapState } from 'vuex'

export default {
  methods: {
    ...mapActions('home',['add','sub'])
    ...mapActions(['home/add','home/sub'])
    }
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到