我对 Vue/VueX 有点陌生,所以肯定有一些我不理解的东西。
我有一个非常简单的组件:
- 它从 VueX
mapState
(incomputed()
)中获取一组项目 - 我从中获取一个项目(
mounted()
目前) - 然后我需要将该项目推送到模板,但我无法弄清楚
我理解的方式,我们只能将数据推送到模板 fromsetup
或data
方法,但不能 from mounted
,created
钩子等。这听起来对吗?
在以下示例代码中,如何将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>