组件感觉好像是自定义标签:全局组件,所有的vue实例都可以是使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>component</title>
</head>
<body>
<div id="app">
<my></my>
</div>
<script src="../js/vue.js"></script>
<script>
// 全局组件,所有的vue实例都可以使用
const my = Vue.component("my",{
template: '<div><h1>哈哈哈</h1></div>'
});
const app = new Vue({
el: '#app',
})
</script>
</body>
</html>
局部组件,只有定义了组件的vue实例才可以使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>component</title>
</head>
<body>
<div id="app">
<my></my>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
components: {
// 局部组件
my: {
template: '<div><h1>局部组件</h1></div>'
}
}
})
</script>
</body>
</html>
模板分离:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>component</title>
</head>
<body>
<div id="app">
<my></my>
</div>
<template id="myCn">
<div><h1>模板分离,局部组件</h1></div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
components: {
// 局部组件
my: {
template: '#myCn'
}
}
})
</script>
</body>
</html>
组件传值:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>component</title>
</head>
<body>
<div id="app">
<my></my>
</div>
<template id="myCn">
<div><h1>模板分离,局部组件--组件的属性值:{{title}}</h1></div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
components: {
// 局部组件
my: {
template: '#myCn',
// 因为组件复用的原则,这里
// 要用方法,这样返回的对象就各自拥有,不会共用
data: function () {
return {
title: '最美的不是下雨天,而是与你躲过雨的屋檐'
}
}
}
}
})
</script>
</body>
</html>
自定义属性,props的使用,可以给组件标签加属性。可以加多个
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>component</title>
</head>
<body>
<div id="app">
<my :content="myContent"></my>
</div>
<template id="myCn">
<div><h1>模板分离,局部组件--组件的属性值:{{title}}---{{content}}</h1></div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
myContent: '内容信息'
},
components: {
// 局部组件
my: {
template: '#myCn',
// 因为组件复用的原则,这里
// 要用方法,这样返回的对象就各自拥有,不会共用
data: function () {
return {
title: '最美的不是下雨天,而是与你躲过雨的屋檐'
}
},
props: ['content']
}
}
})
</script>
</body>
</html>
第一种方式:
props: ['movies','cmessage']
第二种方式:
props: {
movies: Array,
cmessage: {
type: String,
default: 'aaa' // 当不适用这个属性,这个值会默认使用
requried: true // 表示必传
}
}
// 如果使用数组时要注意
props: {
movies: {
type: Array,
default: function(){
return [] // 数组时要这样传,不能直接传[]
}
}
}