InterviewSolution
| 1. |
What are props in Vue.js? |
|
Answer» Props - is an option in the parent component to list what properties of the child are to be accessed by the parent. So, it is down-WAY referencing unlike emit which is used in up-way binding from parent to child so that the parent performs some modification on the value passed to it by the child component. In the parent component properties to be passed are listed so that the child component can use those properties as an attribute name and assign a value when referencing the child instance. Vue props allow a parent component to pass DATA to a child component. Props are used for passing data down the component tree; to pass data up the component tree (from child to parent), you can use $emit() or Vuex Create a component in Vue and pass a description object. The description.props field specifies what props the component can receive. The easiest way is to list your props as an array of property names. In the below example, the GREET component takes in a single prop, name. It then uses the name prop in its template. Vue.component('greet', { props: ['name'], template: ` <DIV> Hello, {{name}} </div> ` }); CONST app = new Vue({ template: `<greet name="Universe!"></greet>` });The name prop is passed to greet as a static prop in the above example in the Vue app. In other words, 'Universe' is a hard coded string. To pass dynamic prop (a prop bound to a variable), prefix the name with v-bind: when creating the component: Vue.component('greet', { props: ['name'], // Renders "Hello, Universe" template: ` <div> Hello, {{name}} </div> ` }); const app = new Vue({ data: () => ({ value: 'Universe' }), // Note the `v-bind:` prefix. If you forget it, `greet` will treat // 'value' as a raw string and render "Hello, value" template: `<greet v-bind:name="value"></greet>` });All props follow a one-way binding which is a down-way binding between the child's property and the parent one. i.e., When the parent property is updated then that latest prop value will be passed down to the child, but not the other way (child to the parent which is carried out by emitting events rather than using props). |
|