Vuejs 3 - 如何从除 data() 和 setup() 之外的其他挂钩将数据发送到模板?

Vuejs 3 - How to send data to template from other hooks than data() and setup()?

我对 Vue/VueX 有点陌生,所以肯定有一些我不理解的地方。

我有一个非常简单的组件:

据我了解,我们只能从 setupdata 方法而不是 mountedcreated 挂钩等将数据推送到模板。听起来对吗?

在下面的示例代码中,如何将从 mounted() 中的 items 获得的 item 对象发送到模板?

我无法在 setup 中完成所有操作,因为我的 computed() VueX items 对象在其中尚不可用。关于如何正确实现这个简单目标的任何建议?

<template>
  <p>ID: {{ id }}</p>
  <p>Name:: {{ item.name }}</p>
</template>

<script lang="ts">
import { useRoute } from 'vue-router'
import { ref, computed, watch } from 'vue'
import { mapState, mapActions } from 'vuex'

export default {
  // fetching items from vuex (works)
  computed: mapState({
    items: (state: any) => state.items
  }),
  setup() {
    const route = useRoute()
    // parsing ID from route params (works)
    const id = ref(route.params.id || 'Plants')
    return {
      id,
      // this seems to be the proper way of pushing data to template:
      // item: { name: 'this works from here' }
    }
  },
  mounted() {
    // fetch item by id (works)
    const item: Plant = this.items.find(i => i.id === this.id)

    // TODO: I need to push this to the template but I cannot from here
    return { item }
  }
}
</script>

这种情况下定义另一个计算的 属性 的最佳方法,例如:

export default {
 
  computed:{ ...mapState({//should spread the mapState in order to add other properties
    items: (state: any) => state.items
  }),
  item(){
    const _item: Plant = this.items.find(i => i.id === this.id)
    return  _item;
   }

 },
  setup() {
    const route = useRoute()
    // parsing ID from route params (works)
    const id = ref(route.params.id || 'Plants')
    return {
      id,
     
    }
  },

}

或纯粹使用选项 api :

export default {
 
  computed:{ ...mapState({//should spread the mapState in order to add other properties
    items: (state: any) => state.items
  }),
  item(){
    let id=this.$route.params.id || 'Plants'
    const _item: Plant = this.items.find(i => i.id === id)
    return  _item;
   }

 },

}

<template>
  <p>ID: {{ $route.params.id }}</p>
  <p>Name:: {{ item.name }}</p>
</template>