細談 vue - slot 篇

本篇文章是細談 vue 系列第二篇了,上篇咱們已經細談了 vue 的核心之一 vdom傳送門javascript

今天咱們將分析咱們常用的 vue 功能 slot 是如何設計和實現的,本文將圍繞 普通插槽做用域插槽 以及 vue 2.6.x 版本的 v-slot 展開對該話題的討論。固然還不懂用法的同窗建議官網先看看相關 API 先。接下來,咱們直接進入正文吧html

1、普通插槽

首先咱們看一個咱們對於 slot 最經常使用的例子前端

<template>
  <div class="slot-demo">
    <slot>this is slot default content text.</slot>
  </div>
</template>
複製代碼

而後咱們直接使用,頁面則正常顯示一下內容vue

而後,這個時候咱們使用的時候,對 slot 內容進行覆蓋java

<slot-demo>this is slot custom content.</slot-demo>
複製代碼

內容則變成下圖所示node

對於此,你們可能都能清楚的知道會是這種狀況。今天我就將帶領你們直接看看 vue 底層對 slot 插槽的具體實現。git

一、vm.$slots

咱們開始前,先看看 vueComponent 接口上對 $slots 屬性的定義github

$slots: { [key: string]: Array<VNode> }; 
複製代碼

多的咱不說,咱直接 console 一下上面例子中的 $slots數組

剩下的篇幅將講解 slot 內容如何進行渲染以及如何轉換成上圖內容app

二、renderSlot

看完了具體實例中 slot 渲染後的 vm.$slots 對象,這一小篇咱們直接看看 renderSlot 這塊的邏輯,首先咱們先看看 renderSlot 函數的幾個參數都有哪些

  • renderSlot()
export function renderSlot ( name: string, // 插槽名 slotName fallback: ?Array<VNode>, // 插槽默認內容生成的 vnode 數組 props: ?Object, // props 對象 bindObject: ?Object // v-bind 綁定對象 ): ?Array<VNode> {}
複製代碼

這裏咱們先不看 scoped-slot 的邏輯,咱們只看普通 slot 的邏輯。

const slotNodes = this.$slots[name]
nodes = slotNodes || fallback
return nodes
複製代碼

這裏直接先取值 this.$slots[name] ,若存在則直接返回其對其的 vnode 數組,不然返回 fallback。看到這,不少人可能不知道 this.$slots 在哪定義的。解釋這個以前咱們直接日後看另一個方法

  • renderslots()
export function resolveSlots ( children: ?Array<VNode>, // 父節點的 children context: ?Component // 父節點的上下文,即父組件的 vm 實例 ): { [key: string]: Array<VNode> } {}
複製代碼

看完 resolveSlots 的參數後咱們接着日後過其中具體的邏輯。若是 children 參數不存在,直接返回一個空對象

const slots = {}
if (!children) {
  return slots
}
複製代碼

若是存在,則直接對 children 進行遍歷操做

for (let i = 0, l = children.length; i < l; i++) {
  const child = children[i]
  const data = child.data
  // 若是 data.slot 存在,將插槽名稱當作 key,child 當作值直接添加到 slots 中去
  if ((child.context === context || child.fnContext === context) &&
    data && data.slot != null
  ) {
    const name = data.slot
    const slot = (slots[name] || (slots[name] = []))
    // child 的 tag 爲 template 標籤的狀況
    if (child.tag === 'template') {
      slot.push.apply(slot, child.children || [])
    } else {
      slot.push(child)
    }
  // 若是 data.slot 不存在,則直接將 child 丟到 slots.default 中去
  } else {
    (slots.default || (slots.default = [])).push(child)
  }
}
複製代碼

slots 獲取到值後,則進行一些過濾操做,而後直接返回有用的 slots

// ignore slots that contains only whitespace
for (const name in slots) {
  if (slots[name].every(isWhitespace)) {
    delete slots[name]
  }
}
return slots

// isWhitespace 相關邏輯
function isWhitespace (node: VNode): boolean {
  return (node.isComment && !node.asyncFactory) || node.text === ' '
}
複製代碼

數組 every() 方法傳送門 - Array.prototype.every()

  • initRender()

咱們從上面已經知道了 vueslots 是如何進行賦值保存數據的。而在 src/core/instance/render.jsinitRender 方法中則是對 vm.$slots 進行了初始化的賦值。

const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
複製代碼
  • genSlot()

瞭解了是 vm.$slots 這塊邏輯後,確定有人會問:你這不就只是拿到了一個對象麼,怎麼把其中的內容給搞出來呢?別急,咱們接着就來說一下對於 slot 這塊 vue 是如何進行編譯的。這裏咱就把 slot generate 相關邏輯過上一過,話很少說,咱直接上代碼

function genSlot (el: ASTElement, state: CodegenState): string {
  const slotName = el.slotName || '"default"' // 取 slotName,若無,則直接命名爲 'default'
  const children = genChildren(el, state) // 對 children 進行 generate 操做
  let res = `_t(${slotName}${children ? `,${children}` : ''}`
  const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}` // 將 attrs 轉換成對象形式
  const bind = el.attrsMap['v-bind'] // 獲取 slot 上的 v-bind 屬性
  // 若 attrs 或者 bind 屬性存在可是 children 卻木得,直接賦值第二參數爲 null
  if ((attrs || bind) && !children) {
    res += `,null`
  }
  // 若 attrs 存在,則將 attrs 做爲 `_t()` 的第三個參數(普通插槽的邏輯處理)
  if (attrs) {
    res += `,${attrs}`
  }
  // 若 bind 存在,這時若是 attrs 存在,則 bind 做爲第三個參數,不然 bind 做爲第四個參數(scoped-slot 的邏輯處理)
  if (bind) {
    res += `${attrs ? '' : ',null'},${bind}`
  }
  return res + ')'
}
複製代碼

注:上面的 slotNamesrc/compiler/parser/index.jsprocessSlot() 函數中進行了賦值,而且 父組件編譯階段用到的 slotTarget 也在這裏進行了處理

function processSlot (el) {
  if (el.tag === 'slot') {
    // 直接獲取 attr 裏面 name 的值
    el.slotName = getBindingAttr(el, 'name')
    // ...
  }
  // ...
  const slotTarget = getBindingAttr(el, 'slot')
  if (slotTarget) {
    // 若是 slotTarget 存在則直接取命名插槽的 slot 值,不然直接爲 'default'
    el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
    if (el.tag !== 'template' && !el.slotScope) {
      addAttr(el, 'slot', slotTarget)
    }
  }
}
複製代碼

隨即在 genData() 中使用 slotTarget 進行 data 的數據拼接

if (el.slotTarget && !el.slotScope) {
  data += `slot:${el.slotTarget},`
}
複製代碼

此時父組件將生成如下代碼

with(this) {
  return _c('div', [
    _c('slot-demo'),
    {
      attrs: { slot: 'default' },
      slot: 'default'
    },
    [ _v('this is slot custom content.') ]
  ])
}
複製代碼

而後當 el.tagslot 的狀況,則直接執行 genSlot()

else if (el.tag === 'slot') {
  return genSlot(el, state)
}
複製代碼

按照咱們舉出的例子,則子組件最終會生成如下代碼

with(this) {
  // _c => createElement ; _t => renderSlot ; _v => createTextVNode
  return _c(
    'div',
    {
      staticClass: 'slot-demo'
    },
    [ _t('default', [ _v('this is slot default content text.') ]) ]
  )
}
複製代碼

2、做用域插槽

上面咱們已經瞭解到 vue 對於普通的 slot 標籤是如何進行處理和轉換的。接下來咱們來分析下做用域插槽的實現邏輯。

一、vm.$scopedSlots

瞭解以前仍是老規矩,先看看 vueComponent 接口上對 $scopedSlots 屬性的定義

$scopedSlots: { [key: string]: () => VNodeChildren };
複製代碼

其中的 VNodeChildren 定義以下:

declare type VNodeChildren = Array<?VNode | string | VNodeChildren> | string;
複製代碼

先來個相關的例子

<template>
  <div class="slot-demo">
    <slot text="this is a slot demo , " :msg="msg"></slot>
  </div>
</template>

<script> export default { name: 'SlotDemo', data () { return { msg: 'this is scoped slot content.' } } } </script>
複製代碼

而後進行使用

<template>
  <div class="parent-slot">
    <slot-demo>
      <template slot-scope="scope">
        <p>{{ scope.text }}</p>
        <p>{{ scope.msg }}</p>
      </template>
    </slot-demo>
  </div>
</template>
複製代碼

效果以下

從使用層面咱們能看出來,子組件的 slot 標籤上綁定了一個 text 以及 :msg 屬性。而後父組件在使用插槽使用了 slot-scope 屬性去讀取插槽帶的屬性對應的值

注:說起一下 processSlot() 對於 slot-scope 的處理邏輯

let slotScope
if (el.tag === 'template') {
  slotScope = getAndRemoveAttr(el, 'scope')
  // 兼容 2.5 之前版本 slot scope 的用法(這塊有個警告,我直接忽略掉了)
  el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope')
} else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {
  el.slotScope = slotScope
}
複製代碼

從上面的代碼咱們能看出,vue 對於這塊直接讀取 slot-scope 屬性並賦值給 AST 抽象語法樹的 slotScope 屬性上。而擁有 slotScope 屬性的節點,會直接以 **插槽名稱 namekey、自己爲 value **的對象形式掛載在父節點的 scopedSlots 屬性上

else if (element.slotScope) { 
  currentParent.plain = false
  const name = element.slotTarget || '"default"'
  ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
}
複製代碼

而後在 src/core/instance/render.jsrenderMixin 方法中對 vm.$scopedSlots 則是進行了以下賦值:

if (_parentVnode) {
  vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
}
複製代碼

而後 genData() 裏會進行如下邏輯處理

if (el.scopedSlots) {
  data += `${genScopedSlots(el, el.scopedSlots, state)},`
}
複製代碼

緊接着咱們來看看 genScopedSlots 中的邏輯

function genScopedSlots ( slots: { [key: string]: ASTElement }, state: CodegenState ): string {
  // 對 el.scopedSlots 對象進行遍歷,執行 genScopedSlot,且將結果用逗號進行拼接
  // _u => resolveScopedSlots (具體邏輯下面一個小節進行分析)
  return `scopedSlots:_u([${ Object.keys(slots).map(key => { return genScopedSlot(key, slots[key], state) }).join(',') }])`
}
複製代碼

而後咱們再來看看 genScopedSlot 是如何生成 render function 字符串的

function genScopedSlot ( key: string, el: ASTElement, state: CodegenState ): string {
  if (el.for && !el.forProcessed) {
    return genForScopedSlot(key, el, state)
  }
  // 函數參數爲標籤上 slot-scope 屬性對應的值 (getAndRemoveAttr(el, 'slot-scope'))
  const fn = `function(${String(el.slotScope)}){` +
    `return ${el.tag === 'template' ? el.if ? `${el.if}?${genChildren(el, state) || 'undefined'}:undefined` : genChildren(el, state) || 'undefined' : genElement(el, state) }}`
  // key 爲插槽名稱,fn 爲生成的函數代碼
  return `{key:${key},fn:${fn}}`
}
複製代碼

咱們把上面例子的 $scopedSlots 打印一下,結果以下

而後上面例子中父組件最終會生成以下代碼

with(this){
  // _c => createElement ; _u => resolveScopedSlots
  // _v => createTextVNode ; _s => toString
  return _c('div',
    { staticClass: 'parent-slot' },
    [_c('slot-demo',
      { scopedSlots: _u([
        {
          key: 'default',
          fn: function(scope) {
            return [
              _c('p', [ _v(_s(scope.text)) ]),
              _c('p', [ _v(_s(scope.msg)) ])
            ]
          }
        }])
      }
    )]
  )
}
複製代碼

二、renderSlot(slot-scope)

  • renderSlot()

上面咱們說起對於插槽 render 邏輯的時候忽略了 slot-scope 的相關邏輯,這裏咱們來看看這部份內容

export function renderSlot ( name: string, fallback: ?Array<VNode>, props: ?Object, bindObject: ?Object ): ?Array<VNode> {
  const scopedSlotFn = this.$scopedSlots[name]
  let nodes
  if (scopedSlotFn) { // scoped slot
    props = props || {}
    // ...
    nodes = scopedSlotFn(props) || fallback
  }
	// ...
	return nodes
}
複製代碼
  • resolveScopedSlots()

這裏咱們看看 renderHelps 裏面的 _u ,即 resolveScopedSlots,其邏輯以下

export function resolveScopedSlots ( fns: ScopedSlotsData, // Array<{ key: string, fn: Function } | ScopedSlotsData> res?: Object ): { [key: string]: Function } {
  res = res || {}
  // 遍歷 fns 數組,生成一個 `key 爲插槽名稱,value 爲函數` 的對象
  for (let i = 0; i < fns.length; i++) {
    if (Array.isArray(fns[i])) {
      resolveScopedSlots(fns[i], res)
    } else {
      res[fns[i].key] = fns[i].fn
    }
  }
  return res
}
複製代碼
  • genSlot

這塊會對 attrsv-bind 進行,對於這塊內容上面我已經提過了,要看請往上翻閱。結合咱們的例子,子組件則會生成如下代碼

with(this) {
  return _c(
    'div',
    {
      staticClass: 'slot-demo'
    },
    [
      _t('default', null, { text: 'this is a slot demo , ', msg: msg })
    ]
  )
}
複製代碼

到目前爲止,對於普通插槽和做用域插槽已經談的差很少了。接下來,咱們將一塊兒看看 vue 2.6.x 版本的 v-slot

3、v-slot

一、基本用法

vue 2.6.x 已經出來有一段時間了,其中對於插槽這塊則是放棄了 slot-scope 做用域插槽推薦寫法,直接改爲了 v-slot 指令形式的推薦寫法(固然這只是個語法糖而已)。下面咱們將仔細談談 v-slot 這塊的內容。

在看具體實現邏輯前,咱們先經過一個例子來先了解下其基本用法

<template>
  <div class="slot-demo">
    <slot name="demo">this is demo slot.</slot>
    <slot text="this is a slot demo , " :msg="msg"></slot>
  </div>
</template>

<script> export default { name: 'SlotDemo', data () { return { msg: 'this is scoped slot content.' } } } </script>
複製代碼

而後進行使用

<template>
  <slot-demo>
    <template v-slot:demo>this is custom slot.</template>
    <template v-slot="scope">
      <p>{{ scope.text }}{{ scope.msg }}</p>
    </template>
  </slot-demo>
</template>
複製代碼

頁面展現效果以下

看着好 easy 。

二、相同與區別

接下來,咱來會會這個新特性

round 1. $slots & $scopedSlots

$slots 這塊邏輯沒變,仍是沿用的之前的代碼

// $slots
const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
複製代碼

$scopedSlots 這塊則進行了改造,執行了 normalizeScopedSlots() 並接收其返回值爲 $scopedSlots 的值

if (_parentVnode) {
  vm.$scopedSlots = normalizeScopedSlots(
    _parentVnode.data.scopedSlots,
    vm.$slots,
    vm.$scopedSlots
  )
}
複製代碼

接着,咱們來會一會 normalizeScopedSlots ,首先咱們先看看它的幾個參數

export function normalizeScopedSlots ( slots: { [key: string]: Function } | void, // 某節點 data 屬性上 scopedSlots normalSlots: { [key: string]: Array<VNode> }, // 當前節點下的普通插槽 prevSlots?: { [key: string]: Function } | void // 當前節點下的特殊插槽 ): any {}
複製代碼
  • 首先,若是 slots 參數不存在,則直接返回一個空對象 {}
if (!slots) {
  res = {}
}
複製代碼
  • prevSlots 存在,且知足系列條件的狀況,則直接返回 prevSlots
const hasNormalSlots = Object.keys(normalSlots).length > 0 // 是否擁有普通插槽
const isStable = slots ? !!slots.$stable : !hasNormalSlots // slots 上的 $stable 值
const key = slots && slots.$key // slots 上的 $key 值
else if (
  isStable &&
  prevSlots &&
  prevSlots !== emptyObject &&
  key === prevSlots.$key && // slots $key 值與 prevSlots $key 相等
  !hasNormalSlots && // slots 中沒有普通插槽
  !prevSlots.$hasNormal // prevSlots 中沒有普通插槽
) {
  return prevSlots
}
複製代碼

注:這裏的 $key , $hasNormal , $stable 是直接使用 vue 內部對 Object.defineProperty 封裝好的 def() 方法進行賦值的

def(res, '$stable', isStable)
def(res, '$key', key)
def(res, '$hasNormal', hasNormalSlots)
複製代碼
  • 不然,則對 slots 對象進行遍歷,操做 normalSlots ,賦值給 keykeyvaluenormalizeScopedSlot 返回的函數 的對象 res
let res
else {
  res = {}
  for (const key in slots) {
    if (slots[key] && key[0] !== '$') {
      res[key] = normalizeScopedSlot(normalSlots, key, slots[key])
    }
  }
}
複製代碼
  • 隨後再次對 normalSlots 進行遍歷,若 normalSlots 中的 keyres 找不到對應的 key,則直接進行 proxyNormalSlot 代理操做,將 normalSlots 中的 slot 掛載到 res 對象上
for (const key in normalSlots) {
  if (!(key in res)) {
    res[key] = proxyNormalSlot(normalSlots, key)
  }
}

function proxyNormalSlot(slots, key) {
  return () => slots[key]
}
複製代碼
  • 接着,咱們看看 normalizeScopedSlot() 都作了些什麼事情。該方法接收三個參數,第一個參數爲 normalSlots,第二個參數爲 key,第三個參數爲 fn
function normalizeScopedSlot(normalSlots, key, fn) {
  const normalized = function () {
    // 若參數爲多個,則直接使用 arguments 做爲 fn 的參數,不然直接傳空對象做爲 fn 的參數
    let res = arguments.length ? fn.apply(null, arguments) : fn({})
    // fn 執行返回的 res 不是數組,則是單 vnode 的狀況,賦值爲 [res] 便可
    // 不然執行 normalizeChildren 操做,這塊主要對針對 slot 中存在 v-for 操做
    res = res && typeof res === 'object' && !Array.isArray(res)
      ? [res] // single vnode
      : normalizeChildren(res)
    return res && (
      res.length === 0 ||
      (res.length === 1 && res[0].isComment) // slot 上 v-if 相關處理
    ) ? undefined
      : res
  }
  // v-slot 語法糖處理
  if (fn.proxy) {
    Object.defineProperty(normalSlots, key, {
      get: normalized,
      enumerable: true,
      configurable: true
    })
  }
  return normalized
}
複製代碼

round 2. renderSlot

這塊邏輯處理其實和以前是同樣的,只是刪除了一些警告的代碼而已。這點這裏就不展開敘述了

round 3. processSlot

首先,這裏解析 slot 的方法名從 processSlot 變成了 processSlotContent,但其實前面的邏輯和之前是同樣的。只是新增了一些對於 v-slot 的邏輯處理,下面咱們就來捋捋這塊。過具體邏輯前,咱們先看一些相關的正則和方法

一、相關正則 & functions
  • dynamicArgRE 動態參數匹配
const dynamicArgRE = /^\[.*\]$/ // 匹配到 '[]' 則爲 true,如 '[ item ]'
複製代碼
  • slotRE 匹配 v-slot 語法相關正則
const slotRE = /^v-slot(:|$)|^#/ // 匹配到 'v-slot' 或 'v-slot:' 則爲 true
複製代碼
  • getAndRemoveAttrByRegex 經過正則匹配綁定的 attr
export function getAndRemoveAttrByRegex ( el: ASTElement, name: RegExp // ) {
  const list = el.attrsList // attrsList 類型爲 Array<ASTAttr>
  // 對 attrsList 進行遍歷,如有知足 RegExp 的則直接返回當前對應的 attr
  // 若參數 name 傳進來的是 slotRE = /^v-slot(:|$)|^#/
  // 那麼匹配到 'v-slot' 或者 'v-slot:xxx' 則會返回其對應的 attr
  for (let i = 0, l = list.length; i < l; i++) {
    const attr = list[i]
    if (name.test(attr.name)) {
      list.splice(i, 1)
      return attr
    }
  }
}
複製代碼
  • ASTAttr 接口定義
declare type ASTAttr = {
  name: string;
  value: any;
  dynamic?: boolean;
  start?: number;
  end?: number
};
複製代碼
  • createASTElement 建立 ASTElement
export function createASTElement ( tag: string, // 標籤名 attrs: Array<ASTAttr>, // attrs 數組 parent: ASTElement | void // 父節點 ): ASTElement {
  return {
    type: 1,
    tag,
    attrsList: attrs,
    attrsMap: makeAttrsMap(attrs),
    rawAttrsMap: {},
    parent,
    children: []
  }
}
複製代碼
  • getSlotName 獲取 slotName
function getSlotName (binding) {
  // 'v-slot:item' 匹配獲取到 'item'
  let name = binding.name.replace(slotRE, '')
  if (!name) {
    if (binding.name[0] !== '#') {
      name = 'default'
    } else if (process.env.NODE_ENV !== 'production') {
      warn(
        `v-slot shorthand syntax requires a slot name.`,
        binding
      )
    }
  }
  // 返回一個 key 包含 name,dynamic 的對象
  // 'v-slot:[item]' 匹配而後 replace 後獲取到 name = '[item]'
  // 進而進行動態參數進行匹配 dynamicArgRE.test(name) 結果爲 true
  return dynamicArgRE.test(name)
    ? { name: name.slice(1, -1), dynamic: true } // 截取變量,如 '[item]' 截取後變成 'item'
    : { name: `"${name}"`, dynamic: false }
}
複製代碼
二、processSlotContent

這裏咱們先看看 slot 對於 template 是如何處理的

if (el.tag === 'template') {
  // 匹配綁定在 template 上的 v-slot 指令,這裏會匹配到對應 v-slot 的 attr(類型爲 ASTAttr)
  const slotBinding = getAndRemoveAttrByRegex(el, slotRE)
  // 若 slotBinding 存在,則繼續進行 slotName 的正則匹配
  // 隨即將匹配出來的 name 賦值給 slotTarget,dynamic 賦值給 slotTargetDynamic
  // slotScope 賦值爲 slotBinding.value 或者 '_empty_'
  if (slotBinding) {
    const { name, dynamic } = getSlotName(slotBinding)
    el.slotTarget = name
    el.slotTargetDynamic = dynamic
    el.slotScope = slotBinding.value || emptySlotScopeToken
  }
}
複製代碼

若是不是 template,而是綁定在 component 上的話,對於 v-slot 指令和 slotName 的匹配操做是同樣的,不一樣點在於因爲這裏須要將組件的 children 添加到其默認插槽中去

else {
  // v-slot on component 表示默認插槽
  const slotBinding = getAndRemoveAttrByRegex(el, slotRE)
  // 將組件的 children 添加到其默認插槽中去
  if (slotBinding) {
    // 獲取當前組件的 scopedSlots
    const slots = el.scopedSlots || (el.scopedSlots = {})
    // 匹配拿到 slotBinding 中 name,dynamic 的值
    const { name, dynamic } = getSlotName(slotBinding)
    // 獲取 slots 中 key 對應匹配出來 name 的 slot
    // 而後再其下面建立一個標籤名爲 template 的 ASTElement,attrs 爲空數組,parent 爲當前節點
    const slotContainer = slots[name] = createASTElement('template', [], el)
    // 這裏 name、dynamic 統一賦值給 slotContainer 的 slotTarget、slotTargetDynamic,而不是 el
    slotContainer.slotTarget = name
    slotContainer.slotTargetDynamic = dynamic
    // 將當前節點的 children 添加到 slotContainer 的 children 屬性中
    slotContainer.children = el.children.filter((c: any) => {
      if (!c.slotScope) {
        c.parent = slotContainer
        return true
      }
    })
    slotContainer.slotScope = slotBinding.value || emptySlotScopeToken
    // 清空當前節點的 children
    el.children = []
    el.plain = false
  }
}
複製代碼

這樣處理後咱們就能夠直接在父組件上面直接使用 v-slot 指令去獲取 slot 綁定的值。舉個官方例子來表現一下

  • Default slot with text
<!-- old -->
<foo>
  <template slot-scope="{ msg }">
    {{ msg }}
  </template>
</foo>

<!-- new -->
<foo v-slot="{ msg }">
  {{ msg }}
</foo>
複製代碼
  • Default slot with element
<!-- old -->
<foo>
  <div slot-scope="{ msg }">
    {{ msg }}
  </div>
</foo>

<!-- new -->
<foo v-slot="{ msg }">
  <div>
    {{ msg }}
  </div>
</foo>
複製代碼

更多例子請點擊 new-slot-syntax 自行查閱

round 4. generate

genSlot() 在這塊邏輯也沒發生本質性的改變,惟一一個改變就是爲了支持 v-slot 動態參數作了些改變,具體以下

// old
const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}`

// new
// attrs、dynamicAttrs 進行 concat 操做,並執行 genProps 將其轉換成對應的 generate 字符串
const attrs = el.attrs || el.dynamicAttrs
    ? genProps(
        (el.attrs || []).concat(el.dynamicAttrs || []).map(attr => ({
          // slot props are camelized
          name: camelize(attr.name),
          value: attr.value,
          dynamic: attr.dynamic
        }))
    	)
    : null
複製代碼

最後

文章到這,對於 普通插槽做用域插槽v-slot 基本用法以及其背後實現原理的相關內容已是結束了,還想要深刻了解的同窗,可自行查閱 vue 源碼進行研究。

老規矩,文章末尾打上波廣告

前端交流羣:731175396

羣裏不按期進行視頻或語音的技術類分享,歡迎小夥伴吧上車,帥哥美女等着大家呢。

我的準備從新撿回本身的公衆號了,以後每週保證一篇高質量好文,感興趣的小夥伴能夠關注一波。

而後,emmm,我要去打籃球了 ~

相關文章
相關標籤/搜索