Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

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

如题,
例如在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>
求解改怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }

  }

};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...