Vue:Component
lastmod 2022-08-31created 2020-08-2814 edits
Components in Vue.
Categories
Component parent-child data flow
In Vue.js, the parent-child component relationship is as follows:
- The parent passes data to the child through
props, (down) - and the child sends messages to the parent through
events. (up)
Vue-components-props-events.png
Things to note when writing components
- Don't use an Object for the value bound by v-model.
Component event
Custom events using v-on: Every Vue instance implements the following events interface.
- Listen to an event using
$on(eventName). - Trigger an event using
$emit(eventName).
In addition, a parent component can listen to events emitted from a child component using v-on directly in the template where the child component is used.
| WARNING |
| |
Example
html file:
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
JavaScript file:
Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
Note that in this example, the child component is completely decoupled from what happens outside of it. All it does is report information about its own activity, in case a parent component might care.
Component registration and naming conventions
When registering a component, it will always be given a name. For example, the global registration we've seen looks like this.
The component's name is the first argument of Vue.component.
The name you give a component may depend on where you intend to use it. When using a component directly in the DOM (as opposed to in a string template or single-file component), we strongly recommend following the W3C rules for custom tag names (all lowercase, with words joined by hyphens (-)). This helps you avoid conflicts with current and future HTML elements.
For other things to keep in mind when naming components, see the Style Guide.
If you pass the object directly without a name (components:{afLoginForm}), it can be used as <af-login-form> in the Template.
how to call child component method from parent vue js
To have a parent component access a child component's method directly, use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})