vue.js - 如果数据尚未持久化到 Vuex,则在兄弟组件之间共享数据?

标签 vue.js vuex

如果我有两个共享相同数据的同级组件,并且该数据已经保存到 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 应该是单向数据流,因此状态信息不会从操作返回到组件,相反组件总是等待数据到达。

要使事物具有反应性,请结合使用 computedgetter

组件

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/

相关文章:

javascript - 当用户在 Vue JS 中的导航容器外单击时如何关闭切换导航

javascript - 了解未记录的 Vue.js 属性 (Vue + Pug)

typescript - 支持 Vue 3 的全日历

javascript - Vuex 不更新使用 mapState 映射的计算变量

vue.js - 从 Vuex 调用 Mixin 全局方法

javascript - 如何使用正确的 isLoading 属性创建默认的 Vuex 状态

javascript - vue计算属性无法获取数据

javascript - 由于 axios get 请求,无法编译 vue.js 应用程序

vue.js - 从 Vuex getter 中的观察者获取值