1. 前言
在这篇文章 vue3事件-钩子-请求 基础上进行 进一步修改
不在过多解释hook
2. hook
1.借鉴
react
写法
2.拆分逻辑,方便使用,发布NPM
也方便
2.1 拆分在这篇文章 vue3事件-钩子-请求 的逻辑
import { reactive,computed} from 'vue'
function useCounter(params) {
console.log("params")
// 响应式对象
const state = reactive({
count: 0,
msg:"提示"
})
//*****************************自定义函数 */
// 点击事件
const add = (event)=>{
state.count ++
}
// 计算属性
const doubleCounter = computed(()=>state.count *2)
// 暴露出去
return{state,add,doubleCounter}
}
export default useCounter
2.2分析
1.把
state
相关逻辑单独拆分出来
3. 使用hook
引入
import useCounter from "./useCounter.js"
核心代码
setup() {
// react API 设计的很像,但是内部实现不一样
const {
state,
add,
doubleCounter
} = useCounter()
// 单值响应式 可以直接用
const anthorCounter = ref(1)
const singState = reactive({
name: ""
})
// ******************* 生命周期 钩子
onMounted(() => {
console.log("mounted 挂载的时候执行")
myFetch.fetchGet("https://xx.yzs.org/v1/cities", {
type: "1"
}).then(res => {
singState.name = res.name
console.log(res);
}).catch(err => {
console.log(err);
})
})
return {
anthorCounter,
...toRefs(state),
...toRefs(singState),
add
}
}
同一个逻辑点 操作在一起,不用来回跳转
4. 封装一个 当前事件的 hook
useTime.js
4.1 简要代码
import { reactive,toRefs ,onMounted} from 'vue'
// 事件检测
function useTime() {
const state = reactive({
time:new Date()
})
onMounted(() => {
console.log("useTime onMounted")
setInterval(()=>{
state.time = new Date()
},1000)
})
return toRefs(state)
}
export default useTime
4.2 分析
1.state就一个时间
2.时间需要在每次加载的时候获取,所以在onMounted
钩子
3.响应式展开
4.3 使用
1.引入
import useTime from "@/xx/useTime.js"
2.数据
export default {
setup () {
// 使用鼠标的逻辑
// 检测逻辑
const {time} = useTime()
// 暴露数据
return{time}
}
}
4.4 模板
<p>time:{{time}}</p>
5. 获取鼠标位置的 Hook
useMouse.js
5.1代码
import { reactive, toRefs ,onMounted,onUnmounted} from 'vue'
// 鼠标位置侦听
function useMouse() {
// 数据响应
const state = reactive({
x:10,
y:10
})
// 事件更新
const update = e=>{
console.log("update",e)
state.x = e.pageX
state.y = e.pageY
}
// 钩子
// 已经加载
onMounted(()=>{
console.log("useMouse onMounted")
window.addEventListener("mousemove",update)
})
//卸载
onUnmounted(() => {
console.log("--------- onUnmounted")
window.removeEventListener("mousemove",update)
})
//转换所有key为响应式数据
return {
...toRefs(state),
update
}
}
export default useMouse
5.2分析
1.鼠标位置需要x,y表示 ,直接使用一个对象具备x,y属性
2.加载的时候监听
3.卸载的时候取消监听逻辑闭环
4.监听函数
5.3 使用
export default {
setup () {
// 使用鼠标的逻辑
const {x,y,update} = useMouse()
// 检测逻辑
const {time} = useTime()
// 暴露数据
return{x,y,time,update}
}
}
5.4 模板
<div>x:{{x}} y:{{y}}</div>
6. hook
1.数据来源清晰 对比之前的写法 Mixin 不会出现磁盘碎片
2.不会出现命名冲突
- 更好的维护性
- 消除 this ,因为this 对 TS不友好
网友评论