如题所示,学习Vue的自定义组件(感觉很有用的样子)
这个部分看的是这本书《vue.js前端开发技术》
作用
1、减少代码冗余量,看着优雅
2、易于找到bug点,对维护的人员比较友好
什么是组件
组件能够扩展HTML元素,封装可重用代码
一般来说,当某一部分需要复用时,才会考虑做成组件。组件是需要将应用抽象为多个相对独立的模块
自定义组件(简单版)
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<title>自定义一个简单的组件</title>
<body>
<div id="app">
<my-component></my-component>//3.这里就是使用我们的标签了
</div>
</body>
<script src=""js/vue.js"></script>
<script>
//1.创建组件
var myComponet = Vue.extend({
template:'<div>我的第一个组件</div>'
})
//2.注册组件myCompnent,并且指定组件的标签<my-component>
Vue.compnent('my-component',myComponent);
new Vue({
el:'#app'
})
</script>
</html>
划重点:
- Vue.extend()创建组件构造器
- Vue.compnent()注册组件
- my-compnent标签使用组件
自定义组件(化简版)
Vue.compnent('my-component',{
template: '<div>WWWW</div>'
});
该版本可以省去第一步
<body>
<template id="myCompnent">
<div>WWWW</div>
</template>
</body>
<script>
Vue.compnent('my-component',{
template: '#myComponent'
});
</script>
这个版本相对来说比较清楚,因为在body里面是以<template>标签来写的,更加符合我的习惯吧
注意的点
但是要注意:当使用DOM 作为模板时,会受到html的限制,因为Vue只有在浏览器解析和标准化HTML后才能获取模板内容,尤其像ul、ol、table、select,限制了能被他包裹的元素,option只能出现在其他某些元素的内部。
简单的例子
<body>
//错误的
<table border ="1">
<tr><th>标题</th></tr>
<my-tr></my-tr>
</table>
//正确的
<table border ="1">
<tr><th>标题</th></tr>
<tr id="my-tr></tr>
</table>
</body>
<script>
Vue.compnent('my-tr',{
template: '<tr>wwwww</tr>'
});
</script>
全局组件和局部组件
从字面上讲:
全局组件:项目里都能用
局部组件:只有当前Vue实例可用
下面看看他们的注册方式吧
<script>
//全局组件
Vue.compnent('global-compnent',{
template: '<b>我是全局组件哈哈哈!!!</b>'
});
//局部组件
var Child = {
template: '<b>我是局部组件呜呜呜~~~</b>'
}
var appk = new Vue({
el:'#app',
components:{
'child-component':Child//这个只有<div id='appk'>的实例才可以用
}
})
</script>
带data的组件
对不起┭┮﹏┭┮,太难打了,我就只打正确版 记录一下吧
<script>
Vue.compnent('counter',{
template: '<button v-on:click="counter += 1">{{ counter} }</botton>',
data: function(){
return{
counter: 0;
}
}
});
带props的组件
<body>
<div id="app">
<my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>
<template id="myComponent">
<table>
<tr>
<td>my name</td>
<td>{{myName}}</td>
</tr>
<tr>
<td>my age</td>
<td>{{myAge}}</td>
</tr>
</table>
</template>
</body>
<script>
var vm =new Vue({
el:'#app',
data:{
name: 'aaa',
age: 23
},
components:{
'my-component':{
template: '#myComponent',
props:['myName','myAge']
//props:{//这些是对属性的限制
// myName:String,
// myAge:Number
//}
}
})
</script>
使用slot
slot为父组件提供了按插内容到子组件中的方法
主要有三种:单slot插槽、具名slot插槽、slot作用域插槽
默认父组件在子组件内套的内容是不显示的,除非子组件模板包含<slot>
1、单slot
<child>
<p>child是组件,这个p就是嵌套的内容,你们是看不见的</p>
</child>
子组件只要这样写就能看见了
child:{
template: '<div><slot><p>实际调用中会被替换掉的</p></slot>这里是子组件</div>'
}
2、具名slot
一个slot不够用,咋办,多加几个呗
<child>
<h1 slot="header">页面标题</h1>
<div slot="footer">
<address>这里有一些联系信息</address>
</div>
</child>
注册的时候
template:
`
<header><slot name="header"></header>
<footer><slot name="footer"></footer>//就是加上这几行就好了
`
3、作用域插槽
懒…🐖…说好累哇┭┮﹏┭┮,下次再写吧