A
A
Alexander2018-12-20 21:05:50
Vue.js
Alexander, 2018-12-20 21:05:50

How to track changes to neighboring Vue components?

Hello dear community!
I am studying Vue and faced the question of how to track changes in neighboring components.
There is a wrapper component in which several descendants are nested.
One of them should track changes in the rest,
something like this: there is a composite PRODUCT that has different parameters
when the user changes some product parameters - the price should be recalculated this.$ store.dispatch ( '
calcPriceAction', params) - a request is sent to the server, which finds the price according to the specified parameters server
because there are changes in the store and it turns out that the computer must change them

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
ZeVeL, 2018-12-21
@ZeVeL

Good afternoon!
Are you sure you need a store for child components? I'd rather pass data from the parent to the children using :value="data" and catch the update of this data via @input="recalculate". Then, each time the data is updated in the child components, the recalculate function will be called, in which you can recalculate as you like.

A
Andrey Sedyshev, 2018-12-21
@ musikant777

Well, let's try to guess on the coffee grounds.
So, there is a certain component, when one of the parameters in the data of which changes, a Vuex action must be performed, which, in turn, must set some parameters for another / other components.
Changes are logical to track (surprise!) in watch:

export default {
  props: {
    paramType: {
      type: String
    },
    productId: {
      type: Number
    }
  },
  data () {
    return {
      param: 123
    }
  },
  watch: {
    param (value) {
      this.$store.dispatch('calcPriceAction', { productId: this.productId, paramType: this.paramType, value })
    }
  }
}

It’s hard for me to imagine the code of the calcPriceAction action, but, PROBABLY, something like
calcPriceAction (context, { productId, paramType, value }) {
    const productApiService = context.getters.productApiService
    return productApiService.getPriceFor(productId, paramType, value)
      .then(price => {
        context.commit('setProductPrice', { productId, price })
      })
  }

The user changes the parameter value
-> the action asks for a price on the updated parameter value,
-> updates the state

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question