Vue的组件注册
1.全局注册:当Vue创建,组件就会被加载,不管该组件使不使用,都会被加载【占内存】【入门程序】
2.局部注册:当我们使用到某个组件,该组件才会被创建,如果不使用该组件,那么该组件不会被创建
全局注册
Vue.component("button-a",{
template:"\n" +
" <button @click=\"count++\">{{count}}</button>",
data:function () {
return{
count:0
}
},
methods:{
}
})
局部注册
let componentA = {
template:"\n" +
" <button @click=\"count++\">{{count}}</button>",
data:function () {
return{
count:0
}
},
methods:{
}
}
new Vue({
el:"#app",
components:{
"component-a":componentA,
}
})
关于data为什么是一个函数

组件注册优化
在组件中编写html结构时,来回复制黏贴,非常麻烦,也很占内存。解决办法是在html里用模板编写,并且和js分离
1、模板需要写在template标签中,template标签写在容器外部
2、在template标签中只能有一个根标签
<body>
<div id="app">
<button-color></button-color>
</div>
<template id="cId">
<div>
<h1>组件</h1>
<h2>阿萨德</h2>
</div>
</template>
</body>
</html>
<script>
let ButtonColor = {
template:"#cId",
data:function () {
}
}
new Vue({
el:"#app",
components:{
ButtonColor
}
})
</script>
is属性
在html中有一些父子标签,在父标签中只能有特定的子标签【严格规范】【table、ul、ol、dl.....】,如果把子标签封装成组件,在父标签中通过传统方式使用组件,那么会出现显示的效果问题,我们需要通过is进行使用组件
<body>
<div id="app">
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody is="ButtonTable">
</tbody>
<tfoot>
<tr>
<td colspan="3">尾部</td>
</tr>
</tfoot>
</table>
</div>
<template id="tId">
<tbody>
<tr>
<td>1</td>
<td>阿斯顿</td>
<td>26</td>
</tr>
</tbody>
</template>
<script>
let ButtonTable = {
template:"#tId",
}
new Vue({
el:"#app",
components:{
ButtonTable
}
})
</script>
</body>
组件嵌套
在一个组件中使用另一个组件
<body>
<div id="app">
<base-color></base-color>
</div>
<template id="color">
<div>
<h1>这是父组件</h1>
<base-colo1></base-colo1>
</div>
</template>
<template id="color1">
<h1 style="color: red">这是子组件</h1>
</template>
</body>
</html>
<script>
// //创建子组件
let BaseColo1 ={
template:"#color1",
}
//创建父组件
let BaseColor ={
template:"#color",
components:{
BaseColo1
}
}
new Vue({
el:"#app",
components:{
BaseColor
}
})
</script>
组件通讯
1.声明属性
在子组件中通过声明props属性来接收数据
// //创建子组件
let BaseColo1 ={
template:"#color1",
props:["msg"]
}
2.传递数据
在父组件中使用子组件时,使用v-bind进行传递数据
<div>
<base-colo1 :msg = "message"></base-colo1>
</div>
3.在子组件中使用接收到的数据
<h2>{{msg}}</h2>
本文探讨了Vue组件的注册方式,包括全局和局部注册,强调局部注册的内存效率。接着介绍了组件优化策略,如使用模板分离HTML和JS。此外,讲解了is属性在解决特定父标签与自定义组件兼容问题上的作用,以及组件嵌套和父子组件间的通信方法,如通过props进行数据传递。
890

被折叠的 条评论
为什么被折叠?



