Search code examples
vue.jsvuex

Vue how to get value from sub component


Here is my use case:

My main page have several sub-components that collect different input from user, finally I want to submit the whole page with all inputs collected. Therefore I want to retrieve the data from sub-component

One option is to use store, but my sub-components are super simple, just some forms, store seems too heavy... Another option is that I can modify prop, although I know this is bad practice, but this approach looks just perfect....

Is it ok to modify prop if my logic is simple?(just collect inputs from user)Or I have to go for Vuex and store


Solution

  • Expanding on excellent answers from Ifaruki and Andres Foronda, another, related option is the use of the sync modifier on the child component's prop.

    Suppose the child component has a prop named name. In the parent component, you can use the sync modifier like this:

    <Child :name.sync="childName"></Child>
    

    Then, in the child component, when the value of the name prop should be updated, don't update it directly. Instead, emit an event that follows the naming convention for sync-able props, which is update:nameOfProp. So in our example, the child component would do this:

    this.$emit('update:name', newName);
    

    The benefit of the sync modifier is that we don't have to write an event handler function in the parent component--Vue does that for us and updates the variable that is bound to the prop automatically.

    You can read more details about the sync modifier in the official docs.