首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vuejs3-如何从data()和setup()以外的其他钩子向模板发送数据?

Vuejs3-如何从data()和setup()以外的其他钩子向模板发送数据?
EN

Stack Overflow用户
提问于 2020-11-23 19:59:35
回答 1查看 247关注 0票数 1

我对Vue/VueX有点陌生,所以肯定有些东西我不明白。

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

它从computed())

  • In (在mapState中)获取一个项目集合(目前在mounted()中)
  • ,我需要将该项推送到模板,但我无法计算出

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

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

我不能在setup中全部完成,因为computed() VueX items对象在那里还不可用。对于如何正确实现这个简单的目标,有什么建议吗?

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-23 20:04:31

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

代码语言:javascript
复制
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,
     
    }
  },

}

或者纯粹使用options api:

代码语言:javascript
复制
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;
   }

 },

}

代码语言:javascript
复制
<template>
  <p>ID: {{ $route.params.id }}</p>
  <p>Name:: {{ item.name }}</p>
</template>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64975508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档