引入模块
在 vue3.0 里面特别加入了一个 hooks 模块的概念,可以直接引入
自定义模块
import { ref, onMounted, onUnmounted } from 'vue'
function useMouseDownHooks() {
let x = ref(0)
let y = ref(0)
onMounted(() => {
document.addEventListener('click', function (e) {
x.value = e.x
y.value = e.y
})
})
onUnmounted(() => {
document.removeEventListener('click', function () {
console.log('移除了')
})
})
return {
x,
y,
}
}
export default useMouseDownHooks
引入模块
<template>
<div>
<span>{{count}}</span>
<span>{{double}}</span>
<div @click="changecount">点击增加</div>
<span> x:{{x}} y:{{y}}</span>
</div>
</template>
<script>
import { ref, computed, reactive, toRefs, onMounted, watch } from 'vue'
import useMouseDownHooks from '../hooks/useMousedown'
export default {
setup() {
onMounted(() => {
console.log('挂在了')
})
const data = reactive({
count: 0,
double: computed(() => {
return data.count * 2
}),
changecount: () => {
data.count++
},
})
let data2 = ref('哈哈')
watch(
[
data2,
() => {
return data.count
},
() => {
return data.double
},
],
(newval, oldval) => {
console.log(newval)
console.log(oldval)
}
)
let { x, y } = useMouseDownHooks()
const result = toRefs(data)
return {
...result,
x,
y,
}
},
}
</script>
<style lang="less" scoped></style>
模块也可以用 reactive 来写
import { reactive, onMounted, onUnmounted, toRefs } from 'vue'
function useMouseDownHooks() {
const data = reactive({
x: 0,
y: 0,
})
onMounted(() => {
document.addEventListener('click', function (e) {
data.x = e.x
data.y = e.y
})
})
onUnmounted(() => {
document.removeEventListener('click', function () {
console.log('移除了')
})
})
let { x, y } = toRefs(data)
return {
x,
y,
}
}
export default useMouseDownHooks