Vue3逻辑复用及内置组件

 Vue3的逻辑复用主要通过“组合式函数”、“自定义指令”及“插件”来实现。提高了代码复用性,增强代码可维护性及促进团队合作。

1 逻辑复用

1.1 组合式函数

利用Vue组合式API来封装和复用有状态逻辑的函数。对组合式函数有如下约定:

  1. 命名,用驼峰法,并以use作开头。
  2. 输入参数,可以接收ref或getter类型的参数,最好用toValue()函数处理下这种类型的参数。
  3. 推荐始终返回一个包含多个ref的普通的非响应式对象。这样对该对象在组件中解构后仍可以保持响应性。
  4. 确保在onUnmounted()时清理副作用。
  5. 组合式函数只能在<script setup>或setup()钩子中被调用。也只能被同步调用。
import { ref, toValue, watchEffect} from "vue";
import type {Ref} from "vue"
export function useFetch(url: string | Ref<any> ) {
    const data = ref(null)
    const error = ref(null)
    const fetchFun = () => {
        data.value = null
        error.value = null
        fetch(toValue(url))
            .then((res) => res.json())
            .then((json) => (data.value = json))
            .catch((err) => (error.value = err))
    }
    watchEffect(() => {
        fetchFun()
    })
    return { data, error }
}

1.2 自定义指令

重用涉及普通元素的底层DOM访问的逻辑。一个自定义指令由一个包含类似组件生命周期钩子的对象来定义。

el

指令所绑定的DOM元素。

binding对象

value: 传递给指令的值

oldValue: 之前的值

arg: 传递给指令的参数

modifiers:一个包含修饰符的对象

instance:使用该指令的组件实例

dir: 指令的定义对象

vnode

绑定元素的底层VNode

prevVnode

之前的渲染中指令所绑定元素的VNode,仅在beforeUpdate和updated钩子中使用。

表 钩子函数中的参数

<script setup lang="ts">
const vFocus = {
  mounted(el:HTMLElement,bindObj:{value: any,arg: string,modifiers:object}) {
    el.focus()
    console.log(bindObj)
  }
}
</script>

1.3 插件

能为Vue添加全局功能的工具代码。

一个插件可以是一个拥有install()方法的对象,也可以是install函数本身。它会接收app应用实例和传递给app.use的额外选项作为参数。

它有以下的作用:

  1. 通过app.component()和app.directive()注册一个或多个全局组件或自定义指令。
  2. 通过app.provice 使一个资源可被注入进整个应用。
  3. 向app.config.globalProperties中添加一些全局实例属性和方法。
  4. 一个可能包含上述三种功能的功能库。
//globalProvide.ts
export default {
    install(app:App,options: object) {
        console.log(app,options)
        app.provide("globalProvide",options)
    }
}

// main.ts
app.use(globalProvide,{other: 'hmf',address: '深圳'})

2 内置组件

2.1 Transition

会在一个元素组件进入和离开DOM时应用动画。仅支持单个元素或组件作为其插槽内容。

触发条件:1)v-if、v-show触发。2)<component>切换的动态组件。3)改变元素的key属性。

图 6个应用于进入与离开过渡效果的CSS class

<Transition>有个name 属性,用于声明一个过渡效果名。例如,name设置为custom,则上面的v-enter-from 就变为custom-enter-from。

<script setup lang="ts">
import {ref} from "vue";

const tag = ref(true)
const count = ref(0)
</script>

<template>
<button @click="tag = !tag">tag切换</button>
<button @click="count++">{{ count }}</button>
<div class="transition-container">
  <transition name="custom">
    <div v-if="tag">hello transition</div>
  </transition>
  <transition name="custom">
    <div v-if="tag" :key="count">hello {{ count }}</div>
  </transition>
</div>
</template>

<style scoped>
.custom-enter-active,
.custom-leave-active {
  transition: opacity 0.5s ease;
}

.custom-enter-from,
.custom-leave-to {
  opacity: 0;
}
</style>

2.2 TransitionGroup

会在一个v-for列表中的元素或组件被插入、移动或移除时应用动画。

  1. 默认情况下,它不会渲染一个容器元素,可以传入tag来指定容器元素。
  2. 列表中的每个元素都必须有独一无二的key。
  3. CSS过渡的class会被应用在列表内的元素上,而不是容器元素上。
<script setup lang="ts">
import {ref} from "vue";

let count = 0
const array:Array<number> = []
const arr = ref(array)

function randomOpera(type: number) {
   const pos = Math.floor(Math.random() * arr.value.length)
   if (type == -1) {
     if (arr.value.length === 0) return
     arr.value.splice(pos,1)
   } else {
     arr.value.splice(pos,0,count)
     count++
   }
}
</script>

<template>
<div>
  <button @click="randomOpera(1)">插入</button>
  <button @click="randomOpera(-1)">删除</button>
</div>
<div>
  <transition-group name="custom">
     <div v-for="item in arr" :key="item">{{ item }}</div>
  </transition-group>
</div>
</template>

<style scoped>
.custom-enter-active,
.custom-leave-active {
  transition: opacity 0.5s ease;
}

.custom-enter-from,
.custom-leave-to {
  opacity: 0;
}
</style>

2.3 KeepAlive

在多个组件间动态切换时缓存被移除的组件实例。

可以指定需要被包含/排除的组件,指定形式有:1)字符串。2)正则表达式。3)包含这两个的数组。

被缓存实例的生命周期为:onActivated和onDeactivated。

<script setup lang="ts">
import {ref} from "vue";
import ComponentA from "@/article/components/ComponentA.vue";
import ComponentB from "@/article/components/ComponentB.vue";

const tag = ref(true)
</script>

<template>
<button @click="tag = !tag">tag切换</button>
<keep-alive exclude="ComponentB">
  <component :is="tag ? ComponentA : ComponentB"/>
</keep-alive>
</template>

2.4 Teleport

使得一个组件模版的一部分逻辑上从属于该组件,但其部分DOM可以被渲染到该组件之外的其他HTML节点。

<script setup lang="ts">
import {ref} from "vue";

const tag = ref(false)
</script>

<template>
<div class="a6-container">
  <div>
    <button @click="tag = !tag">切换tag</button>
  </div>
  <teleport to="body" v-if="tag">
    <div class="model">
        Hello Teleport
    </div>
  </teleport>
</div>
</template>

<style scoped>
.model {
  background: rgba(229, 231, 231, 0.44);
  position: fixed;
  width: 50%;
  height: 50%;
  left: 25%;
  top: 25%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值