1.onMounted和onBeforeUnmount生命周期
<script>
import {reactive,onMounted, onBeforeUnmount} from 'vue'
export default {
setup(){
let coordinates=reactive({
X:0,
Y:0
})
//封装成一个方法函数
function savePoint(event){
coordinates.X=event.pageX
coordinates.Y=event.pageY
}
//DOM元素挂载完 给window增加一个点击事件
onMounted(()=>{
window.addEventListener('click',savePoint)
})
//销毁之前 移除点击事件
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return {
coordinates
}
}
}
</script>
2.运用hoot (简单来说就是一个JS封装的方法)
先创建一个文件夹目录
在index.js写封装的方法
import { reactive, onMounted, onBeforeUnmount } from 'vue'
export default function () {
let coordinates = reactive({
X: 0,
Y: 0
})
function savePoint(event) {
coordinates.X = event.pageX
coordinates.Y = event.pageY
}
//DOM元素挂载完
onMounted(() => {
window.addEventListener('click', savePoint)
})
//销毁之前 移除点击事件
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
return coordinates
}
最后引用
<template>
<h1>vue3.0</h1>
<h3>X坐标{{userList.X}}</h3>
<h3>Y坐标{{userList.Y}}</h3>
</template>
<script>
//引用的路径
import userCoord from './hoots/index'
export default {
setup(){
//调用方法 然后接收 注意接收的变量不能跟引用的方法用同一个
let userList=userCoord()
//最后return出去
return {
userList
}
}
}
</script>