如果我有两个共享相同数据的同级组件,并且该数据未已经保存到 Vuex
(例如,直接页面加载到 api/v1/calendars/:id
,是否有必要在两个组件中调用该资源?我已阅读以下内容:
Vue components should be as self-contained and isolated as much as possible
如果这是真的,那么从两个组件中请求来自 Vuex
的数据是正确的,但是如果该数据在Vuex
。
理想情况下,我想对所需资源进行一次网络调用,然后该页面上的多个组件都在 Vuex
中共享数据。
我会在两个组件中复制这段代码,特别是 created()
方法。
<script>
import store from '@state/store'
import { calendarComputed } from '@state/helpers'
export default {
data() {
return {
calendar: null,
}
},
computed: {
...calendarComputed,
},
created() {
// Are calendars already persisted?
if (!this.calendars.length) {
store.dispatch('calendar/getCalendars').then((res) => {
this.calendar = res.find((calendar) => { if (calendar.id == this.$route.params.id) return calendar })
})
} else {
this.calendar = this.calendars.find((calendar) => { if (calendar.id == this.$route.params.id) return calendar })
}
},
}
</script>
最佳答案
最简单的方法是让您的组件不(明确地)关心是否已获取日历。
简单地告诉 store 去获取,但是 action 决定它是否真的需要这样做。
Vuex 应该是单向数据流,因此状态信息不会从操作返回到组件,相反组件总是等待数据到达。
要使事物具有反应性,请结合使用 computed
和 getter
。
组件
created() {
/* tell the store 'this is what I need' */
store.dispatch('calendar/getCalendars');
},
...
computed: {
calendar() {
/* reactive - initially null, then gets a value when the store is updated */
return this.$store.getters['calendar/calendarById'](this.$route.params.id)
},
},
商店
getters: {
calendarById: (state) => {
/* return a function so that param can be passed from component */
return (id) => state.calendars ? state.calendars.find(c => c.id === id) : null;
},
}
actions: {
getCalendars (store) {
/* only perform the fetch if the store does not already contain the data */
if (!store.state.calendars) {
fetch(calendarsUrl).then(res => store.commit('setCalendars', res); // e.g
}
},
}
关于vue.js - 如果数据尚未持久化到 Vuex,则在兄弟组件之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250487/