51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

10 个实用技巧助您打造更好的 Vue 应用

10 个实用技巧助您打造更好的 Vue 应用

以下是 10 个实用技巧,让 Vue 应用程序变得更好。

  1. 使用 Composition API<script setup>获得更清晰的组件代码

与 Options API 相比,Composition API 有几个优点,包括:

  • 通过逻辑关注实现更好的组织

  • 更容易重用状态逻辑

  • 并改进了类型AFETY

<script setup>语法提供了使用 Composition API 最直观、最简洁的方法:

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

const count = ref(0) const doubleCount = computed(() => count.value * 2)

function increment() {   count.value++ } </script>

<template>   <button @click="increment">Count is: {{ count }}</button>   <p>Double count is: {{ doubleCount }}</p> </template>

此语法减少了样板代码并使您的组件更具可读性。如果您熟悉 Options API 并想学习 Composition API。

2.杠杆definePropsdefineEmits类型安全道具和发射

使用TypescriptdefinePropsdefineEmits实现更好的类型推断:

<script setup lang="ts">
  const props = defineProps<{
    title: string
    count?: number
  }>()
  
  const emit = defineEmits<{
      change: [id: number];
      update: [value: string];
  }>();
  
  // Usage
  emit('change', 1)
  </script>

这为组件的外部 API 提供了类型安全性,这意味着组件的消费者可以在 IDE 中获得一流的自动完成结果和有用的错误检测(即那些精美的红色波浪线)

image.png


如果您想了解如何最好地利用 TypeScript 和 Vue.js。

3.用于toRefs破坏反应性对象

当你需要解构一个反应性对象时,使用它toRefs来保持反应性:

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

const props = defineProps<{   title: string   count?: number }>()

const { title, count } = toRefs(props)

console.log(title.value) // Will update when props changes </script>

4.为可重复使用的逻辑创建组合

将可重复使用的逻辑提取为组合:


// useCounter.ts
import { ref } from 'vue'

export function useCounter(initial = 0) {   const count = ref(initial)   function increment() {     count.value++   }   return { count, increment } }

// Component.vue <script setup> import { useCounter } from './useCounter'

const { count, increment } = useCounter(10) </script>

这可以促进代码重用并使组件保持整洁。这是我推荐 Composition API 而不是 Options API 的首要原因之一。如果您使用 Composition API 编写组件,那么这些可组合抽象的实现就更加明显了。

  1. 用于watchEffect反应性副作用

watchEffect立即运行一个函数,同时被动跟踪其依赖项:

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

const count = ref(0) const message = ref('')

watchEffect(() => {   message.value = The count is ${count.value} }) </script>

这对于依赖于反应状态的副作用非常有用。

6.杠杆作用provideinject深层道具通过

使用provideinject深度传递数据而无需 props 钻孔:

<!-- Parent.vue -->
<script setup>
import { provide, ref } from 'vue'

const theme = ref('light') provide('theme', theme) </script>

<!-- DeepChild.vue --> <script setup> import { inject } from 'vue'

const theme = inject('theme', 'light') // 'light' is the default value </script>

这简化了向深层嵌套组件传递数据的过程,并且对于许多实际用例来说非常方便。

  1. 用于shallowRef大型物体

处理不需要深度反应性的大型物体时,使用shallowRef

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

const largeObject = shallowRef({ /* many properties */ })

function updateObject() {   largeObject.value = { /* new large object */ } } </script>


这可以显著提高大型、频繁更新的对象的性能。

8.用于defineExpose控制组件公共接口

<script setup>使用来defineExpose明确控制向父组件公开的内容:

<!-- AppModal.vue -->
<script setup>
import { ref } from 'vue'

const isOpen = ref(false) function open() {   isOpen.value = true  } function close() {   isOpen.value = true  }

defineExpose({ open, close }) </script>

<!-- ParentComponent.vue --> <script setup> const modal = ref(); </script>

<template> <button @click="modal.open()">Open Modal></button> <AppModal ref="modal"> </template>


这可让您对组件的公共 API 进行细粒度控制。

9.effectScope分组效果的杠杆清理

用于effectScope将多个效果组合并清理在一起:


import { effectScope, onScopeDispose } from 'vue'

const scope = effectScope()

scope.run(() => {   // All effects created here will be automatically disposed together   const data = ref(null)   watchEffect(() => {/* ... /})   watch(data, () => {/ ... */}) })

onScopeDispose(() => {   scope.stop() // stop all effects in the scope })

这对于创建设置和拆除多个效果的可组合项特别有用。
通过应用这些 Vue 3 特定的技巧,您可以创建更高效、更易于维护且更强大的 Vue 应用程序。在应用这些技巧时,请记住始终考虑项目的特定需求。

10.在单个文件组件中使用2个脚本标签

Vue 单文件组件中可以有 2 个脚本部分:一个带有属性setup,一个不带有。出于多种原因,这很有用。
其中一个原因是导出与组件紧密相关但可能在其他地方有用的类型或数据。

<!-- UserProfileComponent -->
<script lang="ts">
  export interface UserProfile{
    username: string,
    // etc...
  }
  </script>
  <script setup lang="ts">
  defineProps<UserProfile>()
  </script>

另一种方法是导出紧密耦合组件的提供/注入密钥。

赞(4)
未经允许不得转载:工具盒子 » 10 个实用技巧助您打造更好的 Vue 应用