Search code examples
javascriptreactjsvue.jscomponents

How I can pass attributes directly to component in vuejs, like reactjs


This is example in react.js:

Form.jsx

<FormInput
 type='text'
 name='displayName'
 value={displayName}
 onChange={this.handleChange}
 required
/>

Input.jsx

const FormInput = ({ handleChange, ...otherProps }) => (
    <input className="form-input" onChange={handleChange} {...otherProps} />
)

My question is, how can I pass attributes to other components with spread objects? like react.js


Solution

  • See this page of the documentation. By binding an object using v-bind (without the spread operator), internally Vue.js will extract out each property and pass them as individual props. In your example above, you would do something like this:

    <form-input
        type="text"
        name="displayName"
        required
        v-bind="otherProps"
        v-on:change="handleChange"
    ></form-input>
    

    Doing the above, would be the same as manually passing all of the props one-by-one like so:

    <form-input
        type="text"
        name="displayName"
        required
        v-bind:prop1="otherProps.prop1"
        v-bind:prop2="otherProps.prop2"
        v-bind:prop3="otherProps.prop3"
        ... etc ...
        v-on:change="handleChange"
    ></form-input>