一、组件与复用
注意点
- 代表组件的标签名不支持使用驼峰命名,建议使用
-
分隔符分离单词 - 子组件的
props
属性在HTML
中接收数据的时候不支持驼峰,建议使用-
分隔符分离单词 - 子向父传递传递数据自定义事件不支持驼峰,也不支持
-
,建议全部小写 - 组件的内容必须使用
div
包裹,不然无法渲染到页面 - 修改
props
的属性不影响父组件的数据,但是如果要修改props
最好是通过父组件修改,不然会报错 - 组件内部不能访问
Vue
实例的数据。
1.全局组件注册
//全局组件注册:全局注册的组件在任何Vue实例对应的HTML代码内都能使用
<div>
<my-component></my-component>
</div>
----------------------------------------
Vue.component("my-component",{
template:"<div>这里是组件的内容</div>"
})
const app = new Vue({
el:"#app"//使用全局组件首先需要挂载DOM,不然在HTML代码内无法使用组件
})
下面是效果图:
2.局部组件注册
(1)在Vue根实例内注册
(1)在Vue的实例中,可以使用components来注册组件内容,这样注册后的组件只能在当前Vue实例对应的HTML代码中使用。
--------------------------------------------------------------
<div id="app">
<my-child></my-child>
</div>
--------------------------------------------------------------
let child = {
template: "<div>这里是子组件</div>"
}
let app = new Vue({
el: '#app',
components: {
"my-child": child
//components选项内,key是使用组件时的名字,value则是组件
}
});
(2)在父组件内嵌套注册子组件
(1)组件中也可以使用components来嵌套注册组件.
<div id="app">
<my-father></my-father>
</div>
-------------------------------------
let child = {
template: "<div>这是子组件</div>"
}
let father = {
template: `
<div>
这是父组件
<my-child></my-child>//这里使用了注册的子组件
</div>
`,
components: {
'my-child': child
//在父组件中注册的子组件并不能在Vue实例对应的HTML中使用,只能在父组件中使用
}
}
let app = new Vue({
el: '#app',
components: {
'my-father': father
}
});
下面是渲染之后的结构图
3.使用template模板标签
- 使用
template
标签模板可以让代码不臃肿
el: '#app',
components: {
'my-component':{
template:"<div>当组件代码过多时就会显的臃肿,此时可以使用template标签</div>"
}
}
- 使用
template
<div id="app">
<mycpn></mycpn>
</div>
<template id="my-template">
<div>
这是使用了template标签的组件
</div>
</template>
-------------------------------------------
let myTemplate = {
template: "#my-template" }
//注意:template属性对应的是template标签的id
let app = new Vue({
el: '#app',
components: {
mycpn: myTemplate
}
});
4.HTML语法导致组件使用受限
解释:在某些标签内只能使用特定的标签,比如table
只能使用tr
,th
,这种情况下能使用特殊的属性来挂载组件
1.首先看不使用特殊属性挂载
<div id="app">
<table>
<tbody>
<my-component></my-component>
</tbody>
</table>
</div>
-----------------------------------------
Vue.component("my-component", {
template: "<div>这里是组件的内容</div>"
})
DOM图
使用特殊属性挂载
<div id="app">
<table>
<tbody is="my-component"></tbody>
</table>
</div>
------------------------------------