父子组件嵌套使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<cpn2></cpn2>
</div>
<script src="../js/vue.js"></script>
<script>
// 1.创建第一个 vue 组件实例
// 子 组件
const cpn1 = Vue.extend({
template: `
<div>
<h2>哈哈哈</h2>
</div>
`
});
// 2.创建第二个 vue 组件实例
// 父 组件
// 其实在这个组件实例中我们可以引用其他组件,如下:
const cpn2 = Vue.extend({
// 子组件的标签先在父组件中进行注册,然后把标签在父组件的 template 中引入
template: `
<div>
<h3>呵呵呵</h3>
<cpn1></cpn1>
</div>
`,
components: {
cpn1: cpn1
}
});
// 3.root 组件: 局部注册组件
const app = new Vue({
el: '#vue',
data: {
message: '你好!华为'
},
// 在root 根节点中,注册了哪些组件,在 html 中才能引用
components: {
cpn2: cpn2
}
});
</script>
</body>
</html>
组件语法糖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<cpn1></cpn1>
<cpn2></cpn2>
</div>
<script src="../js/vue.js"></script>
<script>
// Vue 为了简化这个过程,提供了注册的语法糖
// 主要是省去了调用Vue.extend(),而是可以直接使用一个对象来代替
// 1.语法糖 : 全局组件注册
Vue.component('cpn1', {
template: `
<div>
<h3>哈哈哈</h3>
</div>
`,
})
// 2.语法糖 :局部组件注册
const app = new Vue({
el: '#vue',
data: {
message: '你好!华为'
},
components: {
'cpn2': {
template: `
<div>
<h3>呵呵呵</h3>
</div>
`,
}
}
});
</script>
</body>
</html>
组件模板分离
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<cpn></cpn>
<cpn2></cpn2>
</div>
<!--第一种写法-->
<!--script 标签,注意类型必须是 text/x-template -->
<script type="text/x-template" id="cpn">
<div>
<h2>我是标题</h2>
<p>我是内容,哈哈哈</p>
</div>
</script>
<!--第二种写法-->
<!--template标签-->
<template id="cpn2">
<div>
<h2>我是标题</h2>
<p>我是内容,哈哈哈</p>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
Vue.component('cpn', {
template: '#cpn'
})
Vue.component('cpn2', {
template: '#cpn2'
})
const app = new Vue({
el:'#vue',
data:{
message:'你好!华为'
}
});
</script>
</body>
</html>