局部组件
局部组件直接挂载到Vue下面
上代码:
<!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">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
</div>
<!-- 此时下面的无法显示 -->
<div id="app2">
<cpn></cpn>
</div>
<script src="../js/vue.js"></script>
<script>
// 1. 创建组件构造器对象
const cpnC = Vue.extend({
template: `
<div>
<h2>title</h2>
<p>main one</p>
<p>main two</p>
</div>
`
})
const app = new Vue({
el: '#app',
data: {
message: 'hello'
},
components: {
// cpn使用组件时的标签名
cpn: cpnC
}
})
const app2 = new Vue({
el: '#app2'
})
</script>
</body>
</html>
全局组件
全局组件用
Vue.component('cpn', cpnC)
进行注册
(全局组件, 意味着可以在多个Vue的实例下面使用)
<!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">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
</div>
<div id="app2">
<cpn></cpn>
</div>
<script src="../js/vue.js"></script>
<script>
// 1. 创建组件构造器对象
const cpnC = Vue.extend({
template: `
<div>
<h2>title</h2>
<p>main one</p>
<p>main two</p>
</div>
`
})
// 2.注册组件(全局组件, 意味着可以在多个Vue的实例下面使用)
Vue.component('cpn', cpnC)
const app = new Vue({
el: '#app',
data: {
message: 'hello'
}
})
const app2 = new Vue({
el: '#app2'
})
</script>
</body>
</html>
组件必须挂载在某个Vue实例下,否则它不会生效
组件语法糖注册方式
<body>
<div id="app">
<cpn1></cpn1>
<cpn2></cpn2>
</div>
<script src="../js/vue.js"></script>
<script>
// 1.全局组件注册的语法糖
// 1.创建组件构造器
// const cpn1 = Vue.extend()
// 2.注册组件(全局组件形式)
Vue.component('cpn1', {
template: `
<div>
<h2>title one</h2>
<p>content one</p>
</div>
`
})
// 2.注册局部组件的语法糖
const app = new Vue({
el: '#app',
data: {
message: 'hello'
},
components: {
'cpn2': {
template: `
<div>
<h2>title two</h2>
<p>content two</p>
</div>
`
}
}
})
</script>
</body>
分离式写法
<body>
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
</div>
<!-- 1.script标签,注意:类型必须是text/x-template -->
<!-- <script type="text/x-template" id="cpn">
<div>
<h2>title</h2>
<p>content happy</p>
</div>
</script> -->
<!-- 2.template 标签 -->
<template id="cpn">
<div>
<h2>title</h2>
<p>content one</p>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
// 1.注册一个全局组件
Vue.component('cpn', {
template: '#cpn'
})
const app = new Vue({
el: '#app',
data: {
message: 'hello'
}
})
</script>
</body>