Vue之组件化开发思想

1. 组件注册

1.1 全局组件注册语法

在这里插入图片描述

1.2 组件用法

在这里插入图片描述

1.3 组件注册注意事项

1. data必须是一个函数

⚫ 分析函数与普通对象的对比

2. 组件模板内容必须是单个跟元素

⚫ 分析演示实际的效果

3. 组件模板内容可以是模板字符串

⚫ 模板字符串需要浏览器提供支持(ES6语法)

4. 组件命名方式

⚫ 短横线方式

Vue.component('my-component', { /* ... */ })

⚫ 驼峰方式

Vue.component('MyComponent', { /* ... */ })

5.组件注册注意事项

如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件,但是
在普通的标签模板中,必须使用短横线的方式使用组件

1.4 局部组件注册

var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }
new Vue({
	el: '#app'
	components: {
	'component-a': ComponentA,
	'component-b': ComponentB,
	'component-c': ComponentC,
}
})

2. 组件间数据交互

2.1 父组件向子组件传值

1. 组件内部通过props接收传递过来的值

Vue.component(‘menu-item', {
props: ['title'],
template: '<div>{{ title }}</div>'
})

2. 父组件通过属性将值传递给子组件

<menu-item title="来自父组件的数据"></menu-item>
<menu-item :title="title"></menu-item>

3. props属性名规则

⚫ 在props中使用驼峰形式,模板中需要使用短横线的形式
⚫ 字符串形式的模板中没有这个限制

Vue.component(‘menu-item', {
// 在 JavaScript 中是驼峰式的
props: [‘menuTitle'],
template: '<div>{{ menuTitle }}</div>'
})
<!– 在html中是短横线方式的 -->
<menu-item menu-title=“nihao"></menu-item>

4. props属性值类型

⚫ 字符串 String
⚫ 数值 Number
⚫ 布尔值 Boolean
⚫ 数组 Array
⚫ 对象 Object

2.2 子组件向父组件传值

1. 子组件通过自定义事件向父组件传递信息

<button v-on:click='$emit("enlarge-text") '>扩大字体</button>

2. 父组件监听子组件的事件

<menu-item v-on:enlarge-text='fontSize += 0.1'></menu-item>

3. 子组件通过自定义事件向父组件传递信息

<button v-on:click='$emit("enlarge-text", 0.1) '>扩大字体</button>

4. 父组件监听子组件的事件

<menu-item v-on:enlarge-text='fontSize += $event'></menu-item>

2.3 非父子组件间传值

1. 单独的事件中心管理组件间的通信

var eventHub = new Vue()                                        

2. 监听事件与销毁事件

eventHub.$on('add-todo', addTodo)
eventHub.$off('add-todo')

3. 触发事件

eventHub.$emit(‘add-todo', id)

在这里插入图片描述

3. 组件插槽

3.1 组件插槽的作用

⚫ 父组件向子组件传递内容
在这里插入图片描述

3.2 组件插槽基本用法

1. 插槽位置

Vue.component('alert-box', {
template: `
<div class="demo-alert-box">
<strong>Error!</strong>
<slot></slot>
</div>
`
})

2. 插槽内容

<alert-box>Something bad happened.</alert-box>

3.3 具名插槽用法

在这里插入图片描述

3.4 作用域插槽

⚫ 应用场景:父组件对子组件的内容进行加工处理
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值