vue3 5个常用的API

Vue3之于Vue2最大的变化,当属composition API了,而除了引入composition API外,一些我们在Vue2上经常使用的东西到了Vue3时也发生了不小的变化,本文将介绍一些有Vue2到Vue3中几个比较重要且常用的知识点。

Options API与Composition API

Options API是把代码分类写在几个Option中:

export default {
  components: {
    
  },
  data() {
    
  },
  computed: {
    
  },
  watch: {
    
  },
  mounted() {
    
  },
}

Composition API没有固定的代码分类,可以自由按自己的逻辑组织代码结构。

当组件比较简单只有一个逻辑的时候,option模式可以很快浏览组件代码,可读性非常高,新手友好。但如果组件代码庞大复杂,option的缺陷就很明显,需要在各Option中横跳才能分清功能模块。这时Composition 模式就更有优势,处理同一个模块的自行组织或者提取hook,而这个需要开发者的自觉,优点即缺点,代码组织不规范就会造成混乱。

image.png

文中代码示例使用setup语法糖 + ts

v-model

支持多个v-model

Vue3中,可以通过参数来达到一个组件支持多个v-model的能力。

// 父组件
<template>
  <child v-model="name" v-model:email="email" />
  <p>姓名:{{ name }}</p>
  <p>邮箱:{{ email }}</p>
</template>

<script lang="ts" setup>
import child from './child.vue'
import { ref } from 'vue'

const name = ref<string>('张三')
const email = ref<string>('666@qq.com')
</script>
// 子组件
<template>
  <button @click="updateName">更新name</button>
  <button @click="updateEmail">更新email</button>
</template>

<script lang="ts" setup>
import {defineEmits} form 'vue'
// 定义emit
const emits = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'update:email', value: string): void
}>()

const updateName = () => {
  emits('update:modelValue', '李四')
}

const updateEmail = () => {
  emits('update:email', '123456@qq.com')
}
</script>

如果v-model没有使用参数,则其默认值为modelValue,如上面的第一个v-model,注意此时不再是像Vue2那样使用$emit('input')了,而是统一使用update:xxx的方式。

废弃.sync

在Vue2中,由于一个组件只支持一个v-model,当我们还有另外的值也想要实现双向绑定更新时,往往用.sync修饰符来实现,而在Vue3中该修饰符已被废弃,因为v-model可以支持多个,所以.sync也就没有存在的必要了。

watch

不同数据类型的监听

基础数据类型的监听:

const name = ref<string>('张三')
watch(name, (newValue, oldValue) => {
  console.log('watch===', newValue, oldValue)
})

复杂数据类型的监听:

interface UserInfo {
  name: string
  age: number
}

const userInfo = reactive<UserInfo>({
  name: '张三',
  age: 10
})
// 监听整个对象
watch(userInfo, (newValue, oldValue) => {
  console.log('watch userInfo', newValue, oldValue)
})

// 监听某个属性
watch(() => userInfo.name,  (newValue, oldValue) => {
  console.log('watch name', newValue, oldValue)
})

支持监听多个源

Vue3里,watch多了一个特性,可以传入一个数组同时侦听多个数据,这比起Vue2确实优雅多了,以往在Vue2中为了实现同时监听多个数据,往往需要借助computed,现在在Vue3里我们可以少一些不必要的代码了。

const name = ref<string>('张三')
const userInfo = reactive({
  age: 18
})

// 同时监听name和userInfo的age属性
watch([name, () => userInfo.age], ([newName, newAge], [oldName, oldAge]) => {
  // 
})

watchEffect

watchEffect与watch的区别

相比Vue2Vue3多watchEffect这个API,watchEffect传入一个函数参数,该函数会立即执行,同时会响应式的最终函数内的依赖变量,并在依赖发生改变时重新运行改函数。

const name = ref<string>('张三')
const age = ref<number>(18)

watchEffect(() => {
  console.log(`${name.value}:${age.value}`) // 张三:18
})

setTimeout(() => {
  name.value = '李四' // 李四:18
}, 3000)

setTimeout(() => {
  age.value = 20 // 李四:20
}, 5000)

和watch的区别:

  • 运行时机不同,watchEffect会立即执行,相当于设置了immediate: truewatch
  • watchEffect无法获取改变前后的值。
  • watch显示的指定依赖源不同,watchEffect会自动收集依赖源。

$attrs

Vue3中,$attrs包含父组件中除props和自定义事件外的所有属性集合。

不同于Vue2$attrs包含了父组件的事件,因此$listenners则被移除了。

// 父组件
<template>
  <child id="root" class="test" name="张三" @confirm="getData" />
</template>

<script lang="ts" setup>
const getData = () => {
  console.log('log')
}
</script>

// 子组件
<template>
  <div>
    <span>hello:{{ props.name }}</span>
  </div>
</template>

<script lang="ts">
export default {
  inheritAttrs: false
}
</script>

<script lang="ts" setup>
import { defineProps, useAttrs} from 'vue'
const props = defineProps(['name'])

const attrs = useAttrs()
console.log('attrs', attrs)
</script>
image.png

使用v-bind即可实现组件属性及事件透传:

// 父组件
<template>
  <child closeable @close="onClose" />
</template>

<script lang="ts" setup>
const onClose = () => {
  console.log('close')
}
</script>

// 子组件
<template>
  <div>
    <el-tag v-bind="attrs">标签</el-tag>
  </div>
</template>
<script lang="ts" setup>
import {useAttrs} from 'vue'
const attrs = useAttrs()
</script>

使用ref访问子组件

Vue2中,使用ref即可访问子组件里的任意数据及方法,但在Vue3中则必须使用defineExpose暴露子组件内的方法或属性才能被父组件所调用。

// 父组件
<template>
  <child ref="childRef" />
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'

const childRef = ref()

onMounted(() => {
  childRef.value.getData()
})
</script>

// 子组件
<script lang="ts" setup>
import { defineExpose } from 'vue'

const getData = () => {
  console.log('getData')
}
const name = ref('张三')

defineExpose({
  getData,
  name
})
</script>

完毕~

学习参考:
vue3文档:https://cn.vuejs.org/guide/introduction.html
https://juejin.cn/post/7139721466722910245#heading-9

最后编辑于:2024-09-09 20:04:29


喜欢的朋友记得点赞、收藏、关注哦!!!

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值