·)hooks
javascript
// useCounter.js
import { ref, onMounted } from 'vue'
export function useCounter() {
const count = ref(0)
const load = () => {
const v = localStorage.getItem('count')
if (v) count.value = Number(v)
}
const save = () => {
localStorage.setItem('count', count.value)
}
const inc = () => {
count.value++
save()
}
onMounted(load) // 生命周期也封装进去
return { count, inc } // 显式导出
}
javascript
<script setup>
import { useCounter } from './useCounter'
const { count, inc } = useCounter() // 哪里需要就引哪里
</script>
<template>
<button @click="inc">{{ count }}</button>
</template>
-
函数级粒度 ;可以
return { a, b }只拿 a。 -
任意嵌套组合:
javascriptexport function useFoo() { const { count, inc } = useCounter() // hook 里再调 hook const double = computed(() => count.value * 2) return { count, double, inc } }
hooks 坑集(易解决)
-
多次调用重复 state
同一 hook 在多个组件调用 → 各有一份 state;需要共享可抽
useStore或pinia。 -
忘记 return
函数没 return → 组件拿不到变量,立即报错,反而更安全。
-
循环调用
hook 里写
onMounted里再调自己 → 无限递归,逻辑一目了然易修。
·)mixins
javascript
// counterMixin.js
export default {
data() {
return { count: 0 }
},
created() {
this.load()
},
methods: {
load() {
const v = localStorage.getItem('count')
if (v) this.count = Number(v)
},
save() {
localStorage.setItem('count', this.count)
},
inc() {
this.count++
this.save()
}
}
}
javascript
// MyComp.vue
import counterMixin from './counterMixin'
export default {
mixins: [counterMixin], // 黑盒注入
created() { // 生命周期合并
console.log('组件自身 created')
}
}
-
只能整体引入;无法只复用其中一部分逻辑。
-
多个 mixins 组合时可能出现链式依赖(A 依赖 B 的 data),调试困难。
mixins 坑集(官方文档自嘲)
-
命名冲突
两个 mixin 都有
load()→ 后者覆盖前者,静默失败。 -
依赖隐式
mixin A 里用
this.user要求组件必须自己声明user,否则运行时undefined。 -
合并策略混乱
data 是深合并,methods 是覆盖,hooks(生命周期)是队列,记忆成本高。
-
来源不明
组件里 20 个字段,不知道谁注入的,IDE 无法跳转。
·)hooks和mixins比较
