组件
组件开发的好处
封装功能代码,提升开发效率
便于团队分工合作
组件的创建方式(三种)
注意:1.模板template中只能有一个根节点。2.组件名字如果采用驼峰命名,需要加上连字符‘-’,比如组件名为indexA 标签名为 index-a
1.使用Vue.extend()和Vue.component()两个方法创建全局组件
- Vue.extend()会返回一个组件的构造器,参数为一个对象,是一些配置项
- Vue.component()会利用Vue.extend()返回的构造器创建一个组件实例,两个参数,一个是组件名字,一个是组件的构造器
// 使用组件(在vue实例控制的区域)
<my-index></my-index>
let index = Vue.extend({
// 指定组件的模板
template: '<div>首页</div>'
})
// 创建一个全局组件 my-index
Vue.component('my-index', index)
2.直接使用Vue.component()创建(本质上还是要调用Vue.extend()方法)
// 2.使用组件
<index></index>
// 1.创建组件
Vue.component('index',{
template: '<div>首页</div>'
})
3.通过指定模板创建
// 2.定义模板(需要在vue实例管辖范围之外)
<template id="tpl">
<div>首页</div>
</template>
// 3.引用组件(在vue实例管辖范围内)
<index></index>
// 1.创建组件
Vue.component('index', {
template: '#tpl'
})
注意:构造Vue实例传入的各种选项大多数都可以在组件中使用,但data必须是一个函数(返回一个对象)
父子组件创建
- 通过components属性创建子组件
// 引用组件
<father></father>
// 创建组件
Vue.component('father',{
template: '<div> <p>父组件</p> <son></son></div>',
// 通过components属性创建子组件
components: {
//创建一个子组件
son: {
template: '<p>子组件</p>'
}
}
})
父组件传值给子组件
父组件怎么传值?(通过属性绑定传值)
子组件怎么接受?(通过props获取属性值)
1.声明props,用来接收从父组件传递过来的值
- props能够获取当前组件身上属性对应的属性值
- props可以跟一个数组,数组里面的值是一个字符串,这个字符串可以当属性
2.在使用子组件的地方,通过v-bind指令给子组件中的props赋值
// 引用组件
<father></father>
// 创建组件
Vue.component('father',{
template: '<div> <p>父组件</p> <son v-bind:sonname="name"></son></div>',
data(){
return {
name: 'zs'
}
},
// 通过components属性创建子组件
components: {
//创建一个子组件
son: {
props: ['sonname'],
template: '<p>子组件{{sonname}}</p>'
}
}
})
子组件传值给父组件
this.$emit 触发当前组件身上一个事件,发送一个值(如果传递多个值,可设置对象,或者数组)
<div id="app">
<father></father>
</div>
具体业务逻辑
Vue.component('father', {
template: `
<div>
<p>父亲年纪大了,记性不好,我儿子告诉我他叫{{mySonName}}</p>
<son @tellFatherMyname="getMySonName"></son>
</div>
`,
data () {
return {
mySonName: '????'
}
},
methods: {
// 这个函数中有一个默认参数,该参数就表示上传上来的值
getMySonName (data) {
// console.log(data);
this.mySonName = data
}
},
components: {
son: {
data () {
return {
myName: '小明'
}
},
template: '<button @click="emitMyname">点击就告诉我爸爸我叫{{myName}}</button>',
methods: {
emitMyname () {
// 子组件传值给父组件需要用到$emit()方法,这个方法可以传递两个参数,一个是事件名称,一个是需要传递的数据
this.$emit('tellFatherMyname', this.myName)
}
}
}
}
})
动态组件
- 利用component标签创建动态组件,他的is属性指向谁,就显示哪个组件(v-bink绑定其is属性)
// 创建动态组件,is属性设置显示内容
<component :is='index'></component>
// 此时显示inde组件
Vue.component('index',{
template: '<div>首页</div>'
})
Vue.component('list',{
template: '<div>列表</div>'
})