组件基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 使用组件 -->
<my-cpn></my-cpn>
</div>
<script src="./vue.js"></script>
<script>
// 1.创建组件构造器对象
const cpnC = Vue .extend({
template: `
<div>
<h2>我是标题</h2>
<p>内容哈哈哈</p>
</div>`
})
// 2.注册组件
Vue.component('my-cpn',cpnC)
const app = new Vue({
el: '#app',
data : {
message : 'fff'
}
})
</script>
</body>
</html>
局部组件 全部组件
局部组件在实例下创建
const app = new Vue({
el: '#app',
data : {
message : 'fff'
},
components: {
// 使用组件的标签名
cpn : cpnC
}
})
全局组件 可以在多个Vue实例下使用
Vue.component('my-cpn',cpnC)
父组件与子组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn2></cpn2>
</div>
<script src="./vue.js"></script>
<script>
// 1.创建第一个组件 子组件
const cpnC1 = Vue.extend({
template: `
<div>
<h2>我是标1题</h2>
<p>内容哈哈哈</p>
</div>`
})
// 创建第二个组件构造器 父组件
const cpnC2 = Vue.extend({
template: `
<div>
<h2>我是标2题</h2>
<p>内容呵呵呵</p>
<cpn1></cpn1>
</div>`,
components : {
cpn1 : cpnC1
}
})
const app = new Vue({
el: '#app',
data : {
message : 'fff'
},
components: {
// 使用组件的标签名
cpn2 : cpnC2
}
})
</script>
</body>
</html>
要想使用组件,要么全局注册,要么Vue实例下注册
注册组件的语法糖写法
// 1.创建组件
const cpnC1 = Vue.extend()
// 注册
Vue.component('cpn1',{
template:`
<div>
<h2>我是标7题</h2>
<p>内容呵呵呵</p>
</div>
`
})
组件模板的抽离写法
script标签,类型必须是 text/x-template
<script type="text/x-template" id="cpn">
<div>
<h2>我是标题</h2>
<p>内sgetgs</p>
</div>
</script>
------------------------------------------------------
// 注册
Vue.component('cpn',{
template:'#cpn'
})
template标签
<template id="cpn">
<div>
<h2>我是标题</h2>
<p>内sgetgs</p>
</div>
</template>