連休3回目の記事ですが、まだまだ基礎知識の部分がとても弱いと感じました。
休みを利用してもう一度見直してみましょう
【vue3】フック関数
フックは本質的に、セットアップで使用される複合 API をカプセル化する関数です。
現在クリックされているマウスの座標を取得することが要件だとします。
<template>
<div>
<h2>当前求和的值为:{
{
sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{
{
point.x }},y:{
{
point.y }}</h2>
</div>
</template>
<script >
import {
ref, reactive, onMounted, onBeforeMount } from "vue";
export default {
name: "demo",
setup() {
let sum = ref(0);
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return {
sum,
point,
};
},
};
</script>
座標を見つけるためにマウスをクリックする必要がある他のページがあると仮定すると、これらのコードをフック関数に入れてコードの再利用を実現できます。src の下に新しい hoos フォルダーを作成し、新しい usePoint.js を作成します
。それを書く方法。
書き方1:
import {
reactive, onMounted, onBeforeMount } from "vue";
function savePoint() {
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return {
point
}
}
export default savePoint
ページ内で使用する
<template>
<div>
<h2>当前求和的值为:{
{
sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{
{
point.x }},y:{
{
point.y }}</h2>
</div>
</template>
<script >
import {
ref} from "vue";
import savePoint from "./hooks/usePoint";
export default {
name: "demo",
setup() {
let sum = ref(0);
const {
point } = savePoint();
watch(point, (newVal, oldVal) => {
console.log("point变了", newVal, oldVal);
});
return {
sum,
point,
};
},
};
</script>
書き方2:
import {
reactive, onMounted, onBeforeMount } from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0,
});
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeMount(() => {
window.removeEventListener("click", savePoint);
});
function savePoint(event) {
(point.x = event.pageX), (point.y = event.pageY);
}
return point
}
ページ内で使用する
<template>
<div>
<h2>当前求和的值为:{
{
sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>当前点击时鼠标的坐标为:x:{
{
point.x }},y:{
{
point.y }}</h2>
</div>
</template>
<script >
import {
ref } from "vue";
import usePoint from "./hooks/usePoint";
export default {
name: "demo",
setup() {
let sum = ref(0);
let point = usePoint();
watch(point, (newVal, oldVal) => {
console.log("point变了", newVal, oldVal);
});
return {
sum,
point,
};
},
};
</script>