Home.vue
<template>
<p>{{a}}</p>
<About @myFn="textFn" />
</template>
<script lang="ts">
import {
computed,
defineComponent,
onMounted,
reactive,
ref,
unref,
} from "vue";
import About from "./About.vue";
import myHooks from "../components/myHooks";
export default defineComponent({
components: {
About,
},
setup() {
//自定义hooks
const { aa, textFn } = myHooks();
onMounted(() => {
console.log("index mounted");
textFn();
});
return {
aa,
textFn,
}
})
About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
<button @click="myFn">子-父</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
//一定的写emits,否则会报错
emits: ["my-fn"],
setup(_, { emit }) {
const myFn = () => {
emit("my-fn");
};
return {
myFn,
};
},
});
</script>
Myhooks.ts
import { ref, onMounted } from "vue";
export default function () {
const aa = ref(1);
function textFn() {
console.log("textFn",'ikun');
}
onMounted(() => {
textFn();
});
return {
aa,
textFn,
};
}