Vue進(jìn)階筆記
-
向上通知 $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 使屬性不會(huì)掛載到 DOM 結(jié)點(diǎn)上
使用 v-bind="$attrs" 繼續(xù)往下傳遞爺爺組件中的所有參數(shù)
-
$listeners
作用: 表示方法的集合
使用 v-on="$listeners" 繼續(xù)向下傳遞爺爺組件中的方法(在爺爺組件中綁定了 @son="son")
在孫子組件中使用, 去觸發(fā) 爺爺組件中的 son 方法
this.$listeners.son()
-
注入數(shù)據(jù)
需求: 希望數(shù)據(jù)被兒子公用, 不希望傳遞來傳遞去
父組件中:
export defalut { provide () { return {parent: this} } }
子組件中:
export defalut { inject: [ 'parent' ] }
this.parent, 即為父組件的實(shí)例, 直接 this.parent.xxxx 就可以使用了(xxxx表示父組件中data的屬性)
注意: 在業(yè)務(wù)組件中不建議經(jīng)常使用
-
ref
說明: ref 可以用到 dom 元素上 獲取的是 dom 結(jié)點(diǎn), 用到組件上可以獲取當(dāng)前的組件, 使用 this.$refs. 即可
-
eventBus
說明: 全局消息總線
Vue.prototype.$eventBus = new Vue();
使用 this.$$eventBus.$emit('event', payload) 發(fā)送消息
使用 this.$$eventBus.$on('event') 監(jiān)聽事件
-
JSX
JSX示例1
父組件中
<template> <div> 實(shí)現(xiàn)輸入個(gè) 值 就 變成 h幾 比如 1 就生成 h1 <Level :t="1">標(biāo)題</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是傳進(jìn)去的參數(shù) --> <List :item="item" :render="render"></List> </div> </template> <script> import List from './components/List.js' export default { components: { Level }, methods: { // 即用戶可以在父組件中控制子組件的樣式, 通過函數(shù)式組件 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="['香蕉', '蘋果', '橘子']"> <!-- 回調(diào)函數(shù) --> <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>
注意: 普通插槽是在父組件中執(zhí)行, 作用域插槽是在父組件中執(zhí)行