❗️
在父组件中注册子组件后,在父组件模板template中使用子组件时,应该把父组件模板内容和子组件标签放在同一个HTML标签内,否则会报错无法显示:<div> 父组件内容 <子组件></子组件> </div>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue.js 创建父组件和子组件</title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id='app'>
<parent-component></parent-component>
</div>
<script type="text/javascript">
//Step 1: 创建子组件
var ChildComponent = Vue.extend({
template: '<p>the child comonent.</p>'
})
//Step 2: 创建父组件,并且注册子组件
var ParentComponent = Vue.extend({
template: '<div><p>the parent component. </p><child-component></child-component></div>',
components: {
'child-component': ChildComponent
}
})
//Step 3: 全局注册父组件,子组件也会同时被渲染出来
Vue.component('parent-component', ParentComponent)
new Vue({
el: '#app'
})
</script>
</body>
</html>