Vue 3 API 盲点

Vue 3 的主要特性

在深入了解 Vue 3 的 API 之前,我们先来回顾一下 Vue 3 的主要特性。Vue 3 带来了许多新特性和改进,包括但不限于:

  • Composition API

  • Teleport

  •  Fragments

  •  Suspense

  •  TypeScript Support

  •  emits

  •  provide 和 inject

Composition API

Composition API 是 Vue 3 中引入的一种新的代码组织方式。它可以让我们更好地组织和复用代码,尤其是在大型项目中。主要的 Composition API 包括 setup 函数、refreactivecomputed 和 watch

setup 函数

setup() 钩子是在组件中使用组合式 API 的入口,通常只在以下情况下使用:

  1. 需要在非单文件组件中使用组合式 API 时。
  2. 需要在基于选项式 API 的组件中集成基于组合式 API 的代码时。
示例代码1:正常使用
<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    // 返回值会暴露给模板和其他的选项式 API 钩子
    return {
      count
    }
  },

  mounted() {
    console.log(this.count) // 0
  }
}
</script>

<template>
  <button @click="count++">{{ count }}</button>
</template>

注意

对于结合单文件组件使用的组合式 API,推荐通过 <script setup> 以获得更加简洁及符合人体工程学的语法。

示例代码2:简洁语法

<template>
  <div>{{ count }}</div>
  <button @click="increment">Increment</button>
</template>

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>

ref

接受一个内部值,返回一个响应式的、可更改的 ref 对象,此对象只有一个指向其内部值的属性 .value

示例代码1:template中使用
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue';

const message = ref('Hello, Vue 3!');
</script>

ref 对象是可更改的,也就是说你可以为 .value 赋予新的值。它也是响应式的,即所有对 .value 的操作都将被追踪,并且写操作会触发与之相关的副作用。

示例代码2:setuo中使用
<script setup>
const count = ref(0)
console.log(count.value) // 0

count.value = 1
console.log(count.value) // 1
</script>

reactive

reactive 用来定义一个响应式的对象,它只能用来定义对象类型的值。

示例代码
<template>
  <div>{{ user.name }}</div>
</template>

<script setup>
import { reactive } from 'vue';

const user = reactive({
  name: 'Alice',
  age: 25
});
</script>

computed

computed 用来定义计算属性,它会根据依赖的值自动更新。

示例代码
<template>
  <div>{{ fullName }}</div>
</template>

<script setup>
import { ref, computed } from 'vue';

const firstName = ref('John');
const lastName = ref('Doe');

const fullName = computed(() => `${firstName.value} ${lastName.value}`);
</script>

watch

watch 用来监听响应式数据的变化,并执行相应的回调。

示例代码
<template>
  <div>{{ count }}</div>
</template>

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});

setInterval(() => {
  count.value++;
}, 1000);
</script>

 

Teleport

Teleport 是 Vue 3 引入的一种新的组件,它可以将组件的内容渲染到 DOM 树中的指定位置。

示例代码:弹窗插入到body节点下
<template>
  <button @click="open = true">Open Modal</button>
  <teleport to="body">
    <div v-if="open" class="modal">
    <p>Hello from the modal!</p>
    <button @click="open = false">Close</button>
  </div>
  </teleport>
</template>

<script setup>
</script>

<style scoped>
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>

Fragments

在 Vue 3 中,组件可以返回多个根节点,这就是 Fragments 的概念。它可以减少不必要的 DOM 包装元素。

示例代码:组件中多个根节点

<template>
 
    <header>Header</header>
    <main>Main Content</main>
    <footer>Footer</footer>
 
</template>

<script setup>
</script>

Suspense

Suspense 组件用于处理异步组件加载时的占位符显示,可以极大地提升用户体验。

示例代码:异步组件加载时占位

<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template>

<script setup>
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
);
</script>

 TypeScript 支持

Vue 3 对 TypeScript 的支持得到了极大改进,使得开发者可以更轻松地在项目中使用 TypeScript。

示例代码
<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  data() {
    return {
      count: 1
    }
  }
})
</script>

<template>
  <!-- 启用了类型检查和自动补全 -->
  {{ count.toFixed(2) }}
</template>

lang="ts" 也可以用于 <script setup>

<script setup lang="ts">
// 启用了 TypeScript
import { ref } from 'vue'

const count = ref(1)
</script>

<template>
  <!-- 启用了类型检查和自动补全 -->
  {{ count.toFixed(2) }}
</template>

emits

emits 选项用于声明组件中可以触发的事件。

示例代码
<template>
  <button @click="handleClick">Click me</button>
</template>

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['customEvent']);

const handleClick = () => {
  emit('customEvent', 'Hello, Vue 3!');
};
</script>

provide 和 inject

provide 和 inject 用于在组件树中传递数据,避免了通过 props 层层传递的麻烦。

示例代码

Parent.vue

<template>
  <Child />
</template>

<script setup>
import { provide } from 'vue';
import Child from './Child.vue';

provide('message', 'Hello from Parent!');
</script>

Child.vue

<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { inject } from 'vue';

const message = inject('message');
</script>

从 Composition API 到 Teleport,从 Fragments 到 Suspense,再到 TypeScript Support,emits,provide和inject,我们深入了解了 Vue 3 带来的种种改进和新特性。

希望这篇文章能够帮助你更好地理解和掌握 Vue 3,提升开发效率,写出更加高效、优雅的代码。

  • 20
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吕彬-前端

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

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

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

打赏作者

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

抵扣说明:

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

余额充值