一、Vue3升级了哪些重要的功能

createApp、emits属性、生命周期、多事件、Fragment、移除.sync

异步组件的写法、移除filter、Teleport、Suspense、Composition API

1、createApp

/*Vue2*/

const app = new Vue({/* 选项 */})

Vue.use()

Vue.mixin()

Vue.component()

Vue.directive()

/*Vue3*/

const app = Vue.createApp({/*选项*/})

app.use()

app.mixin()

app.component()

app.directive()

2、emits

const emits = defineEmits(['updateMessage'])
emits('updateMessage', exampleRef.message)

3、多事件

<button @click="handleClick2(), handleClick3()">发送消息到父组件</button>

4、Fragment

<template>中允许有多个根节点

5、移除 .sync

:title.sync 在Vue3中替换成了 v-modle:title

6、teleport 内置组件

将模板内容渲染到DOM树的指定位置

7、Suspense 内置组件

简化异步内容的加载状态管理

二、Composition API 实现逻辑复用

import { ref, onMounted, onUnmounted } from 'vue'
function useMousePosition() {
    const x = ref(0)
    const y = ref(0)

    function updateMousePosition(event) {
        x.value = event.clientX
        y.value = event.clientY
    }

    onMounted(() => {
        window.addEventListener('mousemove', updateMousePosition)
    })

    onUnmounted(() => {
        window.removeEventListener('mousemove', updateMousePosition)
    })

    return { x, y }
}
export default useMousePosition

//组件中引用并使用
import useMousePosition from './useMousePosition.js'
const { x, y } = useMousePosition()

三、v-model参数

<MousePosition v-model:title="title" />
<input :value="title" @input="$emit('update:title', $event.target.value)" />

四、watch和watchEffect的区别

1、两者都可监听 data 属性变化

2、watch 需要明确监听哪个属性

3、watchEffect会根据其中的属性,自动监听其变化

//watch监听 ref
watch(numberRef, (newVal, oldVal) => {
    console.log('numberRef changed to:', newVal, oldVal)
},
    {
        immediate: true, // 立即执行一次
        deep: true // 深度监听
    }
)
//watch 监听reactive对象属性
watch(() => personObj.name, (newVal, oldVal) => {
    console.log('personObj changed to:', newVal, oldVal)
},
    { immediate: true }
)
watchEffect(() => {
    // 初始化时会执行一次(收集要监听的数据)不需要指定监听对象
    console.log(`numberRef的值变了,现在是:${numberRef.value}`)
})

五、setup中如何获取组件实例

1、在 setup 和其他 Composition API 中没有 this

2、可通过 getCurrentInstance 获取当前实例

3、若使用 Option API 可照常使用 this

<script setup>
import { ref, getCurrentInstance, onMounted} from 'vue'
onMounted(() => {
    console.log(this, '组件被挂载了') // undefined
    const instance = getCurrentInstance()
    console.log(instance, '组件实例') //{}
})
</script>

六、Vue3 为何比 Vue2 快

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

1、PatchFlag

1、编译模板时,动态节点做标记。

2、标记,分不同的类型,如 TEXT PROPS CLASS

3、diff 算法时,可以区分静态节点,以及不同类型动态节点

2、hoistStatic

1、将静态节点的定义,提升到父作用域,缓存起来

2、多个相邻的静态节点,会被合并起来

3、典型的拿空间换时间的优化策略

3、cacheHandler

缓存事件

4、SSR优化

静态节点直接输出,绕过了 vdom

动态节点,还是需要动态渲染

5、tree-shaking

编译时,根据不同情况,引用不同的API

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐