vuex中的mapState辅助函数在vue3.x中的写法

broxlighters
  • 1
新手上路,请多包涵

如题,
例如在vue2.x中的:

computed: {
    ...mapState('tabBar', {
      isShow: (state) => state.isShow,
    }),
    //or: ...mapState('tabBar', ['isShow']),
  },

在vue3.x中改怎么写?
尝试过以下写法:

setup(){
    const isShow = computed(...mapState('tabBar', ['isShow']))
    
    return { isShow }
}
setup(){
    const isShow = computed(
      ...mapState('tabBar', {
        isShow: (state) => state.isShow,
      })
    
    return { isShow }
}

以上写法均报错:TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

setup(){
    computed(
      mapState('tabBar', {
        isShow: (state) => state.isShow,
      })
    )
}
setup(){
    const isShow = computed(
      mapState('tabBar', {
        isShow: (state) => state.isShow,
      })
    )
}

以上写法报错:Property "isShow" was accessed during render but is not defined on instance.
at <App>
求解改怎么写?

回复
阅读 1k
1 个回答

vue3.x中setup 函数执行时期在beforeCreate 之后、created 之前执行
需要非常注意的是在vue3.x的setup 函数中是无法访问到this的
页面渲染数据,以及页面的一些函数事件都需要通过return出去,基本结构如下

import { toRefs, reactive } from "vue";
import { useStore } from "vuex";
export default {

  setup() {

    const state = reactive({
      name: ''
    })
    
    const store = useStore()

    state.name = store.state.Name

    return {
      ...toRefs(state)
    }

  }

};
你知道吗?

宣传栏