Search code examples
vue.jsvuejs2vue-componentv-model

Updating the values sent to child component on user click in vuejs


I have two components in mu app.vue and i will send data from app.vue to my first component(filter component) at the time of page load.

Now based on the user actions in the displayed data in the second component i need to pass new vales back to the first component.

There i am using a and a . Consider one of the props i receive in the first component is "nselectedOption" and i do this in data: { return { selectedOption: this.nselectedOption }} to avoid mutation warning.

Now everytime i update the values for this component from second component, i am seeing changes in "nselectedOption" only and not in "selectedOption". Can you explain why is that ?

I need the updated value into a v-model of . 1. If i use "nselectedOption" it is updating the textbox but while editing the value throws error. 2. If i use "selectedOption" it is not updating the values in the textbox itself.

I have even tried using the computed values to return the value, it works but if i try to change values in other options in the filter component the already updated values displays null or nothing.

Please help me. Is this problem can be solved using State Management Concept or do i have to have a separate compoenent other than App.Vue to do all this so that it would act as a parent/child kinda thing or is there anyother way to overcome this.


Solution

  • Try using watcher. If you watch for nselectedOption, everytime it changes, the watcher will fire and bind the changed value to selectedOption.

    props: ['nselectedOption'],
    data: {
        selectedOption
    },
    watch: {
        nselectedOption: function (val) {
            this.selectedOption = val
        }
    }
    

    Also, if the prop you are watching is an object/array, consider using spread operator if you want to make a local copy to avoid mutation.

    this.someObj = { ...someProp }