对比 vue2 vue3 中响应式地获取 vuex 状态

前言

store 中的状态是响应式的,在组件中调用 store 中的状态仅需要在计算属性中返回即可

参考:

Vuex
Vuex - 组合式API

一、计算变量

vue2 和 vue3 选项式API

假设使用vuex定义了一个状态 isPhone,并通过 Getter 暴露出来

单个状态:

computed: {
    
    
  isPhone() {
    
    
    return this.$store.getters.isPhone
  }
}

多个可以通过 mapGetters 辅助函数:

import {
    
     mapGetters } from 'vuex'

export default {
    
    
  // ...
  computed: {
    
    
  	// 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'isPhone',
      'anotherGetter',
      // ...
    ])
    // 如果你想将一个 getter 属性另取一个名字,使用对象形式
    // ...mapGetters({
    
    
	//   // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
	//   doneCount: 'doneTodosCount'
	// })
  }
}

vue3 组合式API

创建 computed 引用以保留响应性,这与在选项式 API 中创建计算属性等效:

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

const $store = useStore()
// const isPhone = $store.getters.isPhone // 非响应式
const isPhone = computed(() => $store.getters.isPhone)

二、直接在模板中使用

vue 模板中可获取全局变量,如果全局引入了store示例,则无需再在 setup 中引入

<script setup>
</script>
<template>
  <div>{
   
   { $store.getters.isPhone }}</div>
</template>

猜你喜欢

转载自blog.csdn.net/ymzhaobth/article/details/130007563