Vue3 面试题总结1(笔记自用)

目录

1. setup 中如何获取组件实例

2. Vue3 为何比 Vue2 快

3. Vite 是什么

4. Vite 为何启动快

5. Composition API 和 React Hooks 对比


1. setup 中如何获取组件实例

  • 在 setup 和其他 Composition API 中没有 this
  • 可通过 getCurrentInstance 获取当前实例
  • 若使用 Options API 可照常使用 this
<template>
  getInstance
</template>

<script>
import { onMounted, getCurrentInstance } from 'vue'
export default {
  name: 'GetInstance',
  data () {
    return {
      x: 1,
      y: 2
    }
  },
  setup () {
    console.log('this1', this) // undefined

    onMounted(() => {
      console.log('this in unMounted', this) // undefined
      console.log('x in onMounted', instance.data.x) // 1
    })

    const instance = getCurrentInstance()
    console.log('instance', instance)
    // (setup 函数中,实例还没完全初始化,要在 onMounted 中打印 data 值)
    console.log('x in setup', instance.data.x) // undefined
  },
  mounted () {
    console.log('this2', this)
    console.log('x', this.x)
  }
}
</script>

2. Vue3 为何比 Vue2 快

  • Proxy 响应式
  • PatchFlag
  • hoistStatic
  • cacheHandler
  • SSR 优化
  • tree-shaking

3. Vite 是什么

  • 一个前端打包工具,Vue 作者发起的项目
  • 借助 Vue 的影响力,发展较快,和 webpack 竞争
  • 优势:开发环境下无需打包,启动快  

4. Vite 为何启动快

  •  开发环境使用 ES6 Module,无需打包---非常快
  • webpack 需要打包成 ES5
  • 生产环境使用 rollup ,并不会快很多

5. Composition API 和 React Hooks 对比

  • 前者 setup 只会被调用一次,而后者函数会被多次调用
  • 前者无需 useMemo(缓存数据)useCallback(缓存函数),因为 setup 只调用一次
  • 前者无需顾虑调用顺序,而后者需要保证 hooks 的顺序一致
  • 前者 reactive + ref 比后者 useState,要难理解

猜你喜欢

转载自blog.csdn.net/weixin_39763711/article/details/126768000