Responsively get vuex state in vue2 vs. vue3

foreword

storeThe state in is responsive, calling the state in the store in the component only needs to be returned in the computed property

reference:

Vuex
Vuex - Composition API

1. Calculation variables

vue2 and vue3 options API

Suppose a state is defined using vuex isPhoneand Getterexposed

single state:

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

Multiple can be passed through mapGettershelper functions:

import {
    
     mapGetters } from 'vuex'

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

vue3 Composition API

Create computeda reference to preserve reactivity, which is equivalent to creating a computed property in the options API:

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

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

2. Use it directly in the template

Global variables can be obtained in the vue template , ifGlobal importAfter the store example, there is no need to introduce in the setup

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

Guess you like

Origin blog.csdn.net/ymzhaobth/article/details/130007563