目标:
能够知道组件化开发思想
能够知道组件的注册方式
能够说出组件间的数据交互方式
能够说出组件插槽的用法
能够说出Vue调式工具的用法
能够基于组件的方式实现业务功能
目录:
组件化开发思想
组件注册
Vue调试工具用法
组件间数据交互
组件插槽
基于组件的案例
1、组件化开发思想
把不同的功能封装到不同的组件中,组件可以通过组合的方式形成完整意义上的应用。
2、组件注册
2.1、全局组件注册语法
Vue.component(组件名称,{
data:组件数据,
template:组件模板内容
})
定义一个名为button-counter的新组件
Vue.component('button-counter',{ data:function(){ return { count:0 } }, template:'<button v-on:click="count++">点击了{{count}}次</button>' })
2.2、组件用法
<div id="app"> <button-counter></button-counter> </div> //可以多次使用,每个组件之间互不影响 <div id="app"> <button-counter></button-counter> <button-counter></button-counter> <button-counter></button-counter> </div>
2.3、组件注册注意事项
data必须是一个函数
组件模板内容必须是单个根元素
组件模板内容可以是模板字符串
组件命名方式:
短横线方法
Vue.component('my-component',{/*...*/})
驼峰方式
Vue.component('MyComponent',{/*...*/})
注意:如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件,但是在普通的标签模板中,
必须使用短横线的方式使用组件。
2.4、局部组件注册
var ComponentA = { /*...*/ } var ComponentB = { /*...*/ } var ComponentC = { /*...*/ } new Vue({ el:'#app', components:{ 'component-a':ComponentA, 'component-b':ComponentB, 'component-c':ComponentC, } })
3、Vue调试工具用法(Devtools)
克隆仓库
安装依赖包
构建
打开Chrome扩展页面
选中开发者模式
加载已解压的扩展,选择shells/chrome
4、组件间数据交互
4.1、父组件向子组件传值
组件内部通过props接受传递过来的值
Vue.component('menu-item',{ props:['title'], template:'<div>{{title}}</div>' })
父组件通过属性将值传递给子组件
//静态值 <menu-item title="来自父组件数据"></menu-item> //动态值 <menu-item :title="title"></menu-item>
props属性名规则
在props中使用驼峰形式,模板中需要使用短横线的形式
字符串模板中没有这个限制
如下所示:
Vue.component('menu-item',{ //在JavaScript中是驼峰式的 props:['menuTitle'], template:'<div>{{menuTitle}}</div>' }) <!-在html中是短横线方式的--> <menu-item menu-title="nihao"></menu-item>
props属性值类型
字符串String
数值Number
布尔值Boolean
数组Array
对象Object
4.2、子组件向父组件传值
子组件通过自定义事件向父组件传递信息
<button v-on:click='$emit("enlarge-text")'>扩大字体</button>
父组件监听子组件事件
<menu-item v-on:enlarge-text='fontSize += 0.1'><menu-item>
子组件通过自定义事件向父组件传递信息
<button v-on:click='$emit("enlarge-text",0.1)'>扩大字体</button>
父组件监听子组件事件
<menu-item v-on:enlarge-text='fontSize += $event'></menu-item>
4.3、非父子组件间传值
单独的事件中心管理组件间的通信
var eventHub = new Vue()
监听事件与销毁事件
eventHub.$on('add-todo',addTodo)
eventHub.$off('add-todo')
事件触发
eventHub.$emit('add-todo',id)
5、组件插槽
5.1、组件插槽的作用
父组件向子组件传递内容
5.2、组件插槽的基本用法
插槽位置
Vue.component('alert-box',{ template:` <div class="demo-alert-box"> <strong>Error!</strong> <slot></slot> </div> ` })
插槽内容
<alert-box>something bad happened</alert-box>
5.3、具名插槽用法
插槽定义(组件插槽名为base-layout)
<div> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div>
插槽用法
<base-layout> <h1 slot="header">标题内容</h1> <p>主要内容1</p> <p>主要内容1</p> <p slot="footer">底部内容</p> </base-layout>
5.4、作用域插槽
应用场景:父组件对子组件的内容进行加工处理
插槽定义(插槽名称为:fruit-list):
<ul> <li v-for="item in list" v-bind:key = "item.id"> <slot v-bind:item = "item"> {{item.name}} </slot> </li> </ul>
插槽用法:
<fruit-list v-bind:list = "list"> <template slot-scope = "slotProps"> <strong v-if = "slotProps.item.current"> {{slotProps.item.text}} </strong> </template> </fruit-list>