vue 中实现功能复用的方法有两种:自定义 hook: 1. 创建以 use 开头的 javascript 函数;2. 在组件中导入并调用 hook。组合式 api: 1. 使用 ref 创建反应式值;2. 使用函数组合反应式值和函数;3. 在组件中导入和使用组合式 api。

Vue 中 Hooks 实现功能复用的方法
Hooks 是 Vue 3.0 中引入的一种功能强大的机制,允许我们在不修改组件定义的情况下重用逻辑。它为功能复用提供了简洁且灵活的方法。
使用自定义 Hook
自定义 Hook 是一种创建可重用功能的常见方法。它们是普通 JavaScript 函数,以 use 前缀开头。
立即学习“前端免费学习笔记(深入)”;
<code class="javascript">import { ref, watch } from 'vue'
export const useCounter = () => {
const count = ref(0)
watch(count, (newValue) => {
console.log(`Count changed to: ${newValue}`)
})
return {
count,
increment: () => count.value++,
decrement: () => count.value--,
}
}</code>然后,可以在任何组件中使用此自定义 Hook:
<code class="javascript"><template>
<div>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<p>Count: {{ count }}</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/code/10786" title="新快购物系统"><img
src="https://img.php.cn/upload/webcode/000/000/003/176373900197726.jpg" alt="新快购物系统" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/code/10786" title="新快购物系统">新快购物系统</a>
<p>新快购物系统是集合目前网络所有购物系统为参考而开发,不管从速度还是安全我们都努力做到最好,此版虽为免费版但是功能齐全,无任何错误,特点有:专业的、全面的电子商务解决方案,使您可以轻松实现网上销售;自助式开放性的数据平台,为您提供充满个性化的设计空间;功能全面、操作简单的远程管理系统,让您在家中也可实现正常销售管理;严谨实用的全新商品数据库,便于查询搜索您的商品。</p>
</div>
<a href="/xiazai/code/10786" title="新快购物系统" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
</div>
</template>
<script>
import { useCounter } from './useCounter'
export default {
setup() {
const { count, increment, decrement } = useCounter()
return { count, increment, decrement }
},
}
</script></code>利用组合式 API
Vue 3.0 引入了组合式 API,它提供了一组函数,用于创建和组合反应式值和函数。这允许我们轻松地创建可重用的功能。
例如,以下代码创建了一个 useInput Hook,用于管理表单输入:
<code class="javascript">import { ref } from 'vue'
export const useInput = (initialValue) => {
const value = ref(initialValue)
const updateValue = (newValue) => {
value.value = newValue
}
return {
value,
updateValue,
}
}</code>在组件中,可以使用它来创建可重用的输入字段:
<code class="javascript"><template>
<input v-model="input.value" @input="input.updateValue" />
</template>
<script>
import { useInput } from './useInput'
export default {
setup() {
const input = useInput('')
return { input }
},
}
</script></code>结论
通过自定义 Hook 和组合式 API,我们可以轻松地在 Vue 中实现功能复用,从而使我们的代码更具模块化、可维护性和可重用性。









