文章目录
- Vue3 自定义hook
- 概述
- 用法
Vue3 自定义hook
概述
Vue3推荐利用Vue的组合式API函数进行代码封装,这种封装方式统称为自定义hook。
用法
定义 hook/countHook.js:
import {computed, ref, watch} from "vue";
export default (initCount = 0) => {
const msg = ref("hello world");
const count = ref(initCount);
const increase = () => {
count.value++;
};
const doubleCount = computed(() => {
return count.value * 2;
});
watch(doubleCount, (newVal, oldVal) => {
console.log("doubleCount发生变化了", newVal, oldVal);
});
return {
msg,
count,
increase,
doubleCount,
};
}
定义组件 Comp1.vue:
<script setup>
import countHook from '../hooks/countHook.js';
const {msg, count, doubleCount, increase} = countHook();
</script>
<template>
<p>Comp1</p>
<p>msg: {{ msg }}</p>
<p>count: {{ count }}</p>
<p>doubleCount: {{ doubleCount }}</p>
<button @click="increase">increase</button>
</template>
定义组件 Comp2.vue:
<script setup>
import countHook from '../hooks/countHook.js';
const {msg, count, doubleCount, increase} = countHook();
</script>
<template>
<p>Comp2</p>
<p>msg: {{ msg }}</p>
<p>count: {{ count }}</p>
<p>doubleCount: {{ doubleCount }}</p>
<button @click="increase">increase</button>
</template>
使用:
<script setup>
import {markRaw, ref} from "vue";
import Comp1 from "./components/Comp1.vue";
import Comp2 from "./components/Comp2.vue";
const tab = ref(null);
function changeTab(comp) {
tab.value = markRaw(comp);
}
changeTab(Comp1);
</script>
<template>
<h1>自定义hook</h1>
<button @click="changeTab(Comp1)">Comp1</button>
<button @click="changeTab(Comp2)">Comp2</button>
<component :is="tab"></component>
</template>