1.组合式 API 和选项 API
Vue2 提供的编程方式是 Options API,即选项式 API。
在日常的开发功能的时候,我们需要在 data 、methods、computed 之间来回找代码。如果功能非常复杂, data 、methods、computed 等里面的代码就会非常长,不好维护。
后来 Vue3 出现了,它提供的编程方式是 Composition API,即组合式 API。
Vue 的自定义 Hooks 是一种封装可重用逻辑的方式。它允许你将复杂的逻辑提取出来,形成独立的函数,然后在不同的组件中复用。这样可以避免在多个组件中重复编写相同的逻辑,提高代码的可读性和可维护性。
案例1
创建一个简单的计数器 Hooks
import {ref} from 'vue'
export function userCount(){
const count = ref(0)
//+
const increment = ()=>{
count.value++;
}
//-
const decrement = ()=>{
count.value--;
}
return {count,increment,decrement}
}
使用:
<template>
<div>
<p>count: {{ count }}</p>
<el-divider></el-divider> <el-button
type="primary"
@click="increment"
>新增</el-button
>
<el-button type="success" @click="decrement">减少</el-button>
</div>
</template>
<script setup lang="ts">
// 导入 hooks
import { userCount } from "../../hooks/userCount"
// 解构引入
const { count, increment, decrement } = userCount()
</script>
<style lang="scss" scoped></style>
效果如下:
案例2
创建一个监听浏览器窗口大小变化的 Hooks
import { ref, onMounted, onUnmounted } from 'vue'
export function usewinResize() {
const width = ref(window.innerWidth)
const height = ref(window.innerHeight)
const handleResize = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
}
onMounted(() => {
window.addEventListener('resize', handleResize);
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
})
return { width, height };
}
使用:
<template>
<div>
<p>count: {{ count }}</p>
<el-divider></el-divider>
<el-button type="primary" @click="increment">新增</el-button>
<el-button type="success" @click="decrement">减少</el-button>
<el-divider></el-divider>
<p>浏览器窗口宽度: {{ width }}</p>
<p>浏览器窗口高度: {{ height }}</p>
</div>
</template>
<script setup lang="ts">
// 导入 hooks
import { userCount } from "../../hooks/userCount"
import { usewinResize } from "../../hooks/useWinResize"
// 解构引入
const { count, increment, decrement } = userCount()
const { width, height } = usewinResize()
</script>
<style lang="scss" scoped></style>
效果如下:
对您有帮助的话辛苦您关注一下微信公众号哦!谢谢
清宁时光秀