1
头图

ref The internal working principle is very simple, in fact, the instruction ref , :ref or v-bind:ref $refs object, then we can get the corresponding element instance through this.$refs . But due to a little trick in scope inheritance, we still need to pay attention to the element instance we can get from this.$refs . Let me come for you one by one!

In-depth ref How it works

 //文件 ./src/directives/ref.ts

export const ref: Directive = ({
  el,
  ctx: {
    scope: { $refs }
  },
  get,
  effect
}) => {
  let prevRef: any
  effect(() => {
    // 获取指向元素的属性名称
    const ref = get()
    $refs[ref] = el
    // 由于属性名称是可以动态生成的(:ref="name"),若新旧对应的属性名称不同,则清理旧属性
    if (prevRef && ref != prevRef) {
      delete $refs[prevRef]
    }
    prevRef = ref
  })

  return () => {
    prevRef && delete $refs[prevRef]
  }
}

Is this implementation straightforward? Now let's turn our attention to the construction of the context object (Context)

 //文件 ./src/context.ts

export const createScopedContext = (ctx: Context, data = {}) => {
  onst parentScope = ctx.scope
  const mergedScope = Object.create(parentScope)
  Object.defineProperties(mergedScope, Object.getOwnPropertyDescriptors(data))
  // $refs构成$refs对象的原型链
  mergedScope.$refs = Object.create(parentScope.$refs)
  // ......
}

$refs constitutes the prototype chain of the $refs object, then we can refer to the element instance like this

 createApp({
  App: {
    $template: `
    <div ref="container">
      <div v-scope="Modal"></div>
    </div>
    `,
    Modal: {
      $template: `
      <button @click="handleHide">Hide</button>
      `,
      handleHide() {
        this.$refs.container.style.display = 'none'
      }
    }
  }
}).mount('[v-scope]')

Summarize

In the next article "petite-vue source code analysis - detailed explanation of optimization methods template", we will start to solve the problem of user experience to be optimized caused by petite-vue online template and online rendering, so stay tuned.
Respect the original, please indicate the source for reprint: https://www.cnblogs.com/fsjohnhuang/p/16006899.htmlFat Boy John

"Anatomy of Petite-Vue Source Code" booklet

"Petite-Vue Source Code Analysis" combines examples to interpret the source code line by line from online rendering, responsive system and sandbox model, and also makes a detailed analysis of the SMI optimization dependency cleaning algorithm using the JS engine in the responsive system. It is definitely an excellent stepping stone before getting started with Vue3 source code. If you like it, remember to forward it and appreciate it!


肥仔John
2.8k 声望1.8k 粉丝

《Petite-Vue源码剖析》作者