我对Vue/VueX有点陌生,所以肯定有些东西我不明白。
我有一个非常简单的组件:
它从computed())
mapState中)获取一个项目集合(目前在mounted()中)据我所知,我们只能从setup或data方法将数据推送到模板,而不能从mounted、created挂钩等将数据推送到模板中。这听起来对吗?
在下面的示例代码中,如何将从item中的items获得的mounted()对象发送到模板?
我不能在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>发布于 2020-11-23 20:04:31
这种情况下定义另一个计算属性的最佳方法如下:
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:
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>https://stackoverflow.com/questions/64975508
复制相似问题