1

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

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

  • 它从 VueX mapState(in computed())中获取一组项目
  • 我从中获取一个项目(mounted()目前)
  • 然后我需要将该项目推送到模板,但我无法弄清楚

我理解的方式,我们只能将数据推送到模板 fromsetupdata方法,但不能 from mountedcreated钩子等。这听起来对吗?

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

我无法全部完成,setup因为我的computed()VueXitems对象在那里还不可用。关于如何正确实现这个简单目标的任何建议?

<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>
4

1 回答 1

1

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

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>
于 2020-11-23T20:04:31.840 回答