vue-父子组件嵌套的示例

组件注册:

// 注册组件
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})

注册局部组件

var childComponent = Vue.extend({
template: '<p>this is child template</p>'
});
Vue.component("parent",{
template: '<div><p>this is parent template</p><child></child></div>',
components: {
'child': childComponent,//child只能在父组件里使用
}
});

完整的html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<title>vue-demo</title>
</head>
<body>
<h1>vue父子组件嵌套示例</h1>
<div id='app'>
<my-component></my-component>
<parent></parent>
</div>
</body>
<script>
// 注册组件
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 子组件
var childComponent = Vue.extend({
template: '<p>this is child template</p>'
});
// 父组件
Vue.component("parent",{
template: '<div><p>this is parent template</p><child></child></div>',
components: {
'child': childComponent,
}
});
new Vue({
el: '#app',
data: {
}
}) </script>
</html>

注意,组件只能有一个根元素,所以最好使用一个div元素包裹组件模板,否则会提示错误:Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

以下是错误的:

Vue.component("parent",{
template: '<div><p>this is parent template</p></div><child></child>',//组件有多个根元素
components: {
'child': childComponent,
}
});

也可以使用非字符串模板注册组件,如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<title>vue-demo</title>
</head>
<body>
<h1>vue父子组件嵌套示例</h1>
<template id="child">
<p>this is child template</p>
</template>
<template id="parent">
<div>
<p>this is parent template</p>
<child></child>
</div>
</template>
<div id="app">
<parent></parent>
</div>
<script src="vue.js"></script>
<script>
var childComponent = Vue.extend({
template: '#child'
});
Vue.component("parent",{
template: '#parent',
components: {
'child': childComponent,
}
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>

效果是一样的。

(完)

上一篇:JAVA算法两道


下一篇:两道面试题,带你解析Java类加载机制