Component Usage Details
# Component Usage Details
# DOM Template Parsing Caveats
<div id="root">
<table>
<tbody>
<row></row>
<row></row>
<row></row>
</tbody>
</table>
</div>
<script type="text/javascript">
Vue.component('row', {
template: '<tr><td>this is a row</td></tr>'
})
var vm = new Vue({
el: '#root'
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In the code above, when the row component is rendered, the tr node will not be placed inside the tbody. Instead, it gets hoisted to the same level as table. This is because according to HTML specifications, tbody can only contain tr elements. The correct approach is to use the tr tag with the is attribute set to the component name row:
<tbody>
<tr is="row"></tr>
<tr is="row"></tr>
<tr is="row"></tr>
</tbody>
2
3
4
5
Similarly, ul>li, ol>li, and select > option tags also need to be handled this way.
Note that this limitation does not exist if you use templates from the following sources:
- String templates (e.g.,
template: '...') - Single-file components (
.vue) (opens new window) <script type="text/x-template">(opens new window)
# Data in Child Components Must Use a Function Return
Vue.component('row', {
data() {
return {
content: 'this is content'
}
},
template: '<tr><td>{{content}}</td></tr>'
})
2
3
4
5
6
7
8
This design exists because child components may be used multiple times, and each time they are used, the data should be independent. Therefore, a function is needed so that each instance can maintain its own independent copy of the returned object.
This prevents data in different child component instances from affecting each other.
# Manipulating the DOM via ref References
Although it is not recommended to manipulate the DOM directly when using Vue, in some cases we must do so to implement certain features. We can use ref references to access DOM nodes.
<!-- `vm.$refs.p` points to the DOM element node -->
<p ref="p">hello</p>
<!-- `vm.$refs.child` points to the component instance -->
<child-component ref="child"></child-component>
2
3
4
5
ref is used to register reference information for an element or child component. The reference information will be registered on the parent component's $refs object. If used on a regular DOM element, the reference points to the DOM element; if used on a child component, the reference points to the component instance.
Component Instance Object: VueComponent
Open the console and click the button in the demo to view the component instance