【问题标题】:vue.js component not updated after vuex action on another componentvue.js 组件在对另一个组件执行 vuex 操作后未更新
【发布时间】:2019-05-28 08:15:47
【问题描述】:

我有一个渲染预订表的组件;当我在另一个组件中更新我的商店时,表没有更新(但商店确实更新了计算属性;我的猜测是问题与未更新的过滤器有关,但我完全不确定。

为此,我有一个 vuex 商店:

...
const store = new Vuex.Store({
  state: {
    bookings: [],
    datesel: '',
  },
  getters: {
    bookings: (state) => {
        return state.bookings
    },
  },
  mutations: {
    SET_BOOKINGS: (state, bookings) => {
        state.bookings = bookings
    },
  },
  actions: {
    setBookings: ({commit, state}, bookings) => {
        commit('SET_BOOKINGS', bookings)
        return state.bookings
    },
  }
})
export default store;

表格基本上是一个带有过滤器的 v-for:

 <template v-for="booking in getBookings( heure, terrain )">

getBookings 是一个方法:

getBookings(hour, court) {
              return this.$store.state.bookings.filter(booking => booking.heure == hour && booking.terrain == court);
            }

我有另一个组件将通过一种方法更新我的预订状态:

bookCourt() {
                axios.post('http://localhost/bdcbooking/public/api/reservations/ponctuelles',
                  {
                        date: this.datesel,
                        membre_id: '1',
                        heure: this.chosenHour,
                        terrain: this.chosenCourt,
                        saison_id: '1'

                  })

              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);

              })
              .catch(e => {
                this.errors.push(e)
              })
              axios.get('http://localhost/bdcbooking/public/api/getReservationsDate?datesel=' + this.datesel)
              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);
                this.bookings = response.data;

              })
              .catch(e => {
                this.errors.push(e)
              })
              $(this.$refs.vuemodal).modal('hide'); 

            }

虽然 this.bookings 是一个计算属性:

computed: {
          bookings: {
            get () {
                return this.$store.getters.bookings
            },
            set (bookings) {
                return this.$store.dispatch('setBookings', bookings)
                console.log('on lance l action');
            }
          }
    }

【问题讨论】:

  • 你的吸气剂完全没有意义,因为你可以做this.$store.state.bookings 并得到完全相同的东西。您也不需要 setBookings 操作,因为它没有做任何异步操作:只需使用突变 this.$store.commit('SET_BOOKINGS', bookings)

标签: javascript vue.js vuex


【解决方案1】:

您的表格没有更新,因为 getBookings 是一个简单的方法,因此不会根据 vuex 状态更改再次触发该方法。

您可以将此 getBookings 方法设置为计算属性,该属性返回过滤后的结果,并且还会根据状态更改进行更新。

【讨论】:

  • 谢谢,但是如何将参数传递给计算属性?
  • 不,您不能在计算属性中传递参数。相反,您可以使用变量来跟踪商店中的更改并在其更新时调用该方法。
猜你喜欢
  • 2017-06-12
  • 2019-08-12
  • 2023-04-01
  • 1970-01-01
  • 2018-08-23
  • 2019-10-05
  • 2020-12-03
  • 2021-10-13
相关资源
最近更新 更多