助你从Vue2过渡到Vue3的常见使用场景之二

前言

相信有很多人已经学习了 Vue3 的 API 和 新特性,但是令人头疼的是工作中依然使用的是 Vue2,也不知道自己的水平能否上手 Vue3 项目,今天把实践过程中常见使用场景分享给大家,希望对你们有所帮助。

场景一:插槽的使用

在 Vue2 的中一般是通过 slot 属性指定模板的位置,通过 slot-scope 获取作用域插槽的数据,如:

<script setup>
import myChild from './myChild.vue'
</script>

<template>
  <div>parent<div>
  <ChildView>
    <template slot="content" slot-scope="{ msg }">
      <div>{{ msg }}</div>
    </template>
  </ChildView>
</template>

在 Vue3 中则是通过 v-slot 这个指令来指定模板的位置,同时获取作用域插槽的数据,如:

<!-- 父组件 -->
<script setup>
import myChild from './myChild.vue'
</script>

<template>
  <div>parent</div>
  <ChildView>
    <template v-slot:content="{ msg }">
      <div>{{ msg }}</div>
    </template>
  </ChildView>
</template>

<!-- 子组件 -->
<template>
  <div>child</div>
  <slot name="content" msg="vue3!"></slot>
</template>

注意:v-slot 在 Vue2 中也可以使用,但必须是 Vue2.6+ 的版本。

场景二:缓存路由组件

缓存一般的动态组件,Vue3 和 Vue2 的用法是一样的,都是使用 KeepAlive 包裹 Component。但缓存路由组件,Vue3 需要结合插槽一起使用:

// Vue2 中缓存路由组件
<KeepAlive>
  <RouterView />
</KeepAlive>

// Vue3 中缓存路由组件
<RouterView v-slot="{ Component }">
  <KeepAlive>
    <Component :is="Component"></Component>
  </KeepAlive>
</RouterView>

场景三:生命周期

Vue3 的生命周期和 Vue2 相比,有以下改动:

  • Vue3 生命周期钩子都以 on 开头,并且需要在组件中手动导入。
<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  console.log('onMounted')
})
</script>
  • Vue3 取消了 beforeCreatecreated 钩子。如果需要在组件创建前注入逻辑,直接在 < script setup > 中编写同步代码就可以了。如果这几个钩子同时存在,setup 的执行顺序要优先于 beforeCreatecreated
  • Vue3 中组件卸载的钩子名称有变化,beforeDestroy 改为 onBeforeUnmountdestroyed 改为 onUnmounted

场景四:全局 API

Vue2 中的全局属性或全局方法,是在构造函数 Vue 的原型对象上进行添加,如:Vue.prototype.$axios = axios 。但在 Vue3 中,需要在 app 实例上添加:

// main.js
app.config.globalProperties.$axios = axios

在组件中使用:

<script setup>
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
proxy.$axios.get('http://...')
</script>

Vue3 中其他的全局 API,如 directive 、component 等,跟 Vue2 的用法都差不多,只不过一个是在 Vue 上调用,一个是在 app 实例上调用:

// main.js
// 全局自定义指令
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

// 全局自定义组件
import CustomComp from './components/CustomComp.vue'
app.component('CustomComp', CustomComp)

需要注意的是,Vue3 废弃了 filter 这个方法,因为通过函数或 computed 可以实现一样的功能。

常见五:与 TypeScript 结合使用

TypeScript 结合使用,我们只需要在 < script setup > 中添加 lang="ts" 就可以了。下面是一些和 TypeScript 结合使用的例子。

为 props 标注类型

  • 运行时声明。当使用 < script setup > 时,defineProps() 宏函数支持从它的参数中推导类型:
<script setup lang="ts">
const props = defineProps({
  foo: { type: String, required: true },
  bar: Number
})

props.foo // string
props.bar // number | undefined
</script>

这被称为 运行时声明 ,因为传递给 defineProps() 的参数会作为运行时的 props 选项使用。

  • 基于类型的声明。我们还可以通过泛型参数来定义 props 的类型,这种方式更加常用:
<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}

const props = defineProps<Props>()
</script>

这被称为 基于类型的声明 ,编译器会尽可能地尝试根据类型参数推导出等价的运行时选项。这种方式的不足之处在于,失去了定义 props 默认值的能力。为了解决这个问题,我们可以使用 withDefaults 宏函数:

<script setup lang="ts">
interface Props {
  msg?: string
  labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
  msg: 'hello vue3!',
  labels: () => ['one', 'two']
})
</script>

为 ref() 标注类型

  • 默认推导类型。ref 会根据初始化时的值自动推导其类型:
import { ref } from 'vue'

const year = ref(2022)
year.value = '2022' // TS Error: 不能将类型 string 分配给类型 number
  • 通过接口指定类型。有时我们可能想为 ref 内的值指定一个更复杂的类型,可以使用 Ref 这个接口:
import { ref } from 'vue'
import type { Ref } from 'vue'

const year: Ref<string | number> = ref('2022')
year.value = 2022 // 成功!
  • 通过泛型指定类型。我们也可以在调用 ref() 时传入一个泛型参数,来覆盖默认的推导行为:
const year = ref<string | number>('2022')
year.value = 2022 // 成功!

为 reactive() 标注类型

  • 默认推导类型。reactive() 也会隐式地从它的参数中推导类型:
import { reactive } from 'vue'

const book = reactive({ title: 'Vue 3 指引' })
book.year = 2022 // TS Error: 类型 { title: string; } 上不存在属性 year
  • 通过接口指定类型。要显式地指定一个 reactive 变量的类型,我们可以使用接口:
import { reactive } from 'vue'

interface Book {
  title: string
  year?: number
}
const book: Book = reactive({ title: 'Vue 3 指引' })
book.year = 2022 // 成功!

其他 APITypeScript 结合使用的方法和上面大同小异,具体可以参考这篇文章: 何为 Vue3 组件标注 TS 类型,看这篇文章就够了!

小结

以上就是我在 Vue3 项目中遇到最多的场景,如果你掌握了 Vue3 常用的 API 和今天这些场景,相信参与 Vue3 项目的开发是没有问题了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shansec~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值