Vue进阶笔记
-
向上通知 $dispatch
Vue.prototype.$dispatch = function (eventName, value) { let parent = this.$parent while (parent) { parent.$emit(eventName, value) parent = parent.$parent } }
-
向下通知 $broadcast
Vue.prototype.$broadcast = function (eventName, value) { const broadcast = (children) => { children.forEach((child) => { child.$emit(eventName, value) if(child.$children) { broadcast(child.$children) } }) } }
-
$attrs
作用: 表示属性的集合
<template> <div> {{ $attrs }} <Grandson2 v-bind="$attrs"></Grandson2> </div> </template> <script> import Grandson2 from './Grandson2' export default { components: { Grandson2 }, inheritAttrs: false } </script>
添加 inheritAttrs: false 使属性不会挂载到 DOM 结点上
使用 v-bind="$attrs" 继续往下传递爷爷组件中的所有参数
-
$listeners
作用: 表示方法的集合
使用 v-on="$listeners" 继续向下传递爷爷组件中的方法(在爷爷组件中绑定了 @son="son")
在孙子组件中使用, 去触发 爷爷组件中的 son 方法
this.$listeners.son()
-
注入数据
需求: 希望数据被儿子公用, 不希望传递来传递去
父组件中:
export defalut { provide () { return {parent: this} } }
子组件中:
export defalut { inject: [ 'parent' ] }
this.parent, 即为父组件的实例, 直接 this.parent.xxxx 就可以使用了(xxxx表示父组件中data的属性)
注意: 在业务组件中不建议经常使用
-
ref
说明: ref 可以用到 dom 元素上 获取的是 dom 结点, 用到组件上可以获取当前的组件, 使用 this.$refs. 即可
-
eventBus
说明: 全局消息总线
Vue.prototype.$eventBus = new Vue();
使用 this.$$eventBus.$emit('event', payload) 发送消息
使用 this.$$eventBus.$on('event') 监听事件
-
JSX
JSX示例1
父组件中
<template> <div> 实现输入个 值 就 变成 h几 比如 1 就生成 h1 <Level :t="1">标题</Level> </div> </template> <script> import Level from './components/LevelFunctional.js' export default { components: { Level } } </script>
子组件中
JSX语法示例:
export default { props: { t: {} }, render(h) { // createElement // HTML 以 < 开头 { return <h1 on-click={() => {alert(1)}} style={{color: 'red'}>你好</h1> } }
export default { props: { t: {} }, render(h) { // createElement let tag = 'h' + this.t return <tag>{ this.$slots.default }</tag> } }
JSX示例2
父组件中
<template> <div> <!-- item是传进去的参数 --> <List :item="item" :render="render"></List> </div> </template> <script> import List from './components/List.js' export default { components: { Level }, methods: { // 即用户可以在父组件中控制子组件的样式, 通过函数式组件 render (h, data) { return <h1>{data}</h1> } } } </script>
子组件中
export default { props: { render: { type: Function }, item: { type: String } }, render (h) { return this.render(h, this.item) } }
注意: 没有 h 就不能用 jsx 语法
JSX示例3: v-slot scope
父组件中, 其他同上
<template> <div> <List :data="['香蕉', '苹果', '橘子']"> <!-- 回调函数 --> <template v-slot="{item, a}"> <span>{{ item }} {{ a }}</span> </template> </List> </div> </template>
子组件中
<template> <div> <template v-for="(item, index) in data"> <slot :item="item" :a="1"></slot> </template> </div> </template>
注意: 普通插槽是在父组件中执行, 作用域插槽是在父组件中执行