Vue3面试题:20道含答案和代码示例的练习题

  1. Vue3中响应式数据的实现原理是什么?

答:Vue3中使用Proxy对象来实现响应式数据。当数据发生变化时,Proxy会自动触发更新。

const state = {
  count: 0
}

const reactiveState = new Proxy(state, {
  set(target, key, value) {
    target[key] = value
    console.log('数据已更新')
    return true
  }
})

reactiveState.count = 1 // 数据已更新

  1. Vue3中的Composition API是什么?

答:Composition API是Vue3中新增的一种API,它可以让开发者更加灵活地组织和重用组件逻辑。

import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    const doubleCount = computed(() => state.count * 2)

    function increment() {
      state.count++
    }

    return {
      state,
      doubleCount,
      increment
    }
  }
}

  1. Vue3中如何使用自定义指令?

答:Vue3中使用app.directive方法来定义自定义指令。自定义指令需要返回一个对象,其中包含指令钩子函数。

import { createApp } from 'vue'

const app = createApp({})

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

<template>
  <input v-focus>
</template>

  1. Vue3中如何使用Teleport组件?

答:Vue3中使用组件来实现Portal功能。需要将组件放在需要传送的目标位置,并指定to属性。

<template>
  <button @click="showDialog = true">Show Dialog</button>

  <teleport to="body">
    <dialog v-if="showDialog">
      <h1>Dialog Title</h1>
      <p>Dialog Content</p>
      <button @click="showDialog = false">Close</button>
    </dialog>
  </teleport>
</template>

  1. Vue3中如何使用Suspense组件?

答:Vue3中使用组件来实现异步组件加载时的占位符。需要在组件中使用