项目由 Vue2 升级到 Vue3 了,本文包含了 Vue3 项目开发中使用的所有语法,希望所有像他一样还不熟的伙伴快速上手 Vue3 项目开发.
开发文档
获取 this
Vue2 中每个组件里使用 this 都指向当前组件实例,this 上还包含了全局挂载的东西、路由、状态管理等啥啥都有
而 Vue3 组合式 API 中没有 this,如果想要类似的用法,有两种,一是获取当前组件实例,二是获取全局实例,如下自己可以去打印出来看看
<script setup>
import {
getCurrentInstance } from 'vue'
// proxy 就是当前组件实例,可以理解为组件级别的 this,没有全局的、路由、状态管理之类的
const {
proxy, appContext } = getCurrentInstance()
// 这个 global 就是全局实例
const global = appContext.config.globalProperties
</script>
全局注册(属性/方法)
Vue2 中我们要往全局上挂载东西通常就是如下,然后在所有组件里都可以通过 this.xxx 获取到了
Vue.prototype.xxx = xxx
而 Vue3 中不能这么写了,换成了一个能被所有组件访问到的全局对象,就是上面说的全局实例的那个对象,比如在 main.js 中做全局注册
// main.js
import {
createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 添加全局属性
app.config.globalProperties.name = '沐华'
在其他组件中调用
<script setup>
import {
getCurrentInstance } from 'vue'
const {
appContext } = getCurrentInstance()
const global = appContext.config.globalProperties
console.log(global.name) // 沐华
</script>
template
Vue2 中只能有一个根节点,而 Vue3 中支持多个根节点,这个大家都知道
其实本质上 Vue3 每个组件还是一个根节点,因为 DOM 树只能是树状结构的,只是 Vue3 在编译阶段新增了判断,如果当前组件不只一个根元素,就添加一个 fragment 组件把这个多根组件的给包起来,相当于这个组件还是只有一个根节点。而 fragment 跟 keep-alive 一样是一个不会被渲染出来的内置组件
<template>
<div>1</div>
<div>2</div>
</template>
获取 DOM
Vue3 中获取 DOM 如下
<template>
<el-form ref="formRef"></el-form>
<child-component />
</template>
<script setup lang="ts">
import ChildComponent from './child.vue'
import {
getCurrentInstance } from 'vue'
import {
ElForm } from 'element-plus'
// 方法一,这个变量名和 DOM 上的 ref 属性必须同名,会自动形成绑定
const formRef = ref(null)
console.log(formRef.value) // 这就获取到 DOM 了
// 方法二
const {
proxy } = getCurrentInstance()
proxy.$refs.formRef.validate((valid) => {
... })
// 方法三,比如在 ts 里,可以直接获取到组件类型
// 可以这样获取子组件
const formRef = ref<InstanceType<typeof ChildComponent>>()
// 也可以这样 获取 element ui 的组件类型
const formRef = ref<InstanceType<typeof ElForm>>()
formRef.value?.validate((valid) => {
... })
</script>
初始化
Vue2 中进入页面就请求接口,或者其他一些初始化的操作,一般放在 created 或 mounted,而 Vue3 中 beforeCreated 和 created 这俩钩子就不用了,因为 setup 在这俩之前执行,还要这俩的话就多此一举了
所以以前用在 beforeCreated / created / beforeMount / mounted 这几个钩子里的内容,在 Vue3 中可以直接放在 setup 里,或者放在 onMounted/onBeforeMount 里
<script setup>
import {
onMounted } from 'vue'
// 请求接口函数
const getData = () => {
xxxApi.then(() => {
... })
}
onMounted(() => {
getData()
})
</script>
解除绑定
Vue2 中一般清除定时器、监听之类的操作有两种方法:
- 一是用$once 搭配 hook: BeforeDestroy 使用,这个 Vue3 不支持了
- 二是用 beforeDestroy / deactivated 这俩钩子,Vue3 中只是把钩子函数重命名了一下
<script setup>
import {
onBeforeUnmount, onDeactivated } from 'vue'
// 组件卸载前,对应 Vue2 的 beforeDestroy
onBeforeUnmount(() => {
clearTimeout(timer)
window.

本文详细介绍了Vue3的开发,包括没有this的组合式API、全局注册、模板、DOM操作、初始化、解除绑定、ref和reactive的使用、watch和watchEffect的区别、computed的改变、nextTick、mixins与hooks的差异、组件通信、状态管理和路由等方面,旨在帮助开发者快速上手Vue3项目。
最低0.47元/天 解锁文章
291

被折叠的 条评论
为什么被折叠?



