类似,新建一个js
import {ref,reactive, onMounted, onBeforeMount } from "vue";
//实现鼠标打点的hook
export default function activepoint() {
let ispoint = ref('ispoint')
let point = reactive({
x: 0,
y: 0,
});
function savepoint(event) {
console.log(event)
point.x = event.pageX;
point.y = event.pageY;
}
function changeispoint() {
ispoint.value = !ispoint.value
}
onMounted(() => {
window.addEventListener("click", savepoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savepoint);
});
return {
point
};
}
在需要使用的页面上
import userPoint from "../utils/point";
setup() {
const point = userPoint();
return { point };
},
export default {
name: "Demo",
setup() {
let parant =reactive({
name: "乞力马扎罗",
sum:0,
job: {
a: 1,
b: 2,
},
})
return {
name: parant.name,
sum:parant.sum,
};
},
};
return {
name: toRef(parant, "name"),
sum: toRef(parant, "sum"),
a: toRef(parant.job, "a"),
};
<template>
<!-- VUE3组件中的模板结构可以没有根标签 -->
<div>{{parant}}</div>
<div>{{ sum }}</div>
<button @click="sum++">sum++</button>
<div>{{ b }}</div>
<button @click="b++">sum++</button>
</template>
<script>
import { ref, reactive, onMounted, onBeforeMount, toRef } from "vue";
export default {
name: "Demo",
setup() {
let parant = reactive({
name: "乞力马扎罗",
sum: 0,
job: {
a: 1,
b: 2,
},
});
return {
parant,
name: toRef(parant, "name"),
sum: toRef(parant, "sum"), //参数1,想操作哪个对象,参数2,想操作对象里的哪个值
b: ref(parant.job.b),
};
},
};
</script>
<style>
</style>
...toRefs(parant), //只给个想操作的对象即可
<div>{{ job.a }}</div>
<button @click="job.a++">job.a++</button>
...toRefs(parant.job), //只给个想操作的对象即可
setup() {
let parant2 = shallowReactive({
name: "乞力马扎罗",
sum: 0,
b: 2,
job: {
a: 1,
},
});
parant2 = readonly(parant2);
return {
parant2,
};
},