英文:
vue3 composition api script setup, share click event with other components
问题
我正在使用Vue3(使用script setup的组合式API),尝试与其他组件共享点击事件。
<h1 @click="useLink">Header #</h1>
```
const useLink = (e) => {
let section = e.target.closest(".section");
if (router.currentRoute.value.hash !== "#" + section.id) {
router.push("#" + section.id);
}
};
```
注意:这个方法在其他几个组件中重复出现。 ☹️
当用户点击h1时,会调用useLink(),并将该id推送到路由器,从而滚动到相应位置。
谢谢
```
<details>
<summary>英文:</summary>
I am using Vue3 (composition API with script setup) and I am trying to share a click event with other components.
```
<h1 @click="useLink">Header #</h1>
const useLink = (e) => {
let section = e.target.closest(".section");
if (router.currentRoute.value.hash !== "#" + section.id) {
router.push("#" + section.id);
}
};
Note: This method is repeated in few other components. ☹️
When a user clicks on h1, useLink() gets called and pushes that id to router which scrolls to position.
Thanks
答案1
得分: 1
link.js
import { useRouter } from 'vue-router';
export function useLink() {
const router = useRouter();
function goToSection(e) {
const section = e.target.closest('.section');
if (router.currentRoute.value.hash !== '#' + section.id) {
router.push('#' + section.id);
}
}
return {
goToSection
};
}
component.vue
<script setup>
import { useLink } from '@/composables/link';
const { goToSection } = useLink();
</script>
<template>
<div class="section" id="one">
.
.
.
<h1 @click="goToSection">Scroll to section div</h1>
</div>
</template>
英文:
A composable should export a function that returns some reusable logic (in this case, another function)
link.js
import { useRouter } from 'vue-router';
export function useLink() {
const router = useRouter();
function goToSection(e) {
const section = e.target.closest('.section');
if (router.currentRoute.value.hash !== '#' + section.id) {
router.push('#' + section.id);
}
}
return {
goToSection
};
}
Then in any component you need this reusable function: import the file, destructure the reusable function, and apply it to your @click
handlers.
component.vue
<script setup>
import { useLink } from '@/composables/link';
const { goToSection } = useLink();
</script>
<template>
<div class="section" id="one">
.
.
.
<h1 @click="goToSection">Scroll to section div</h1>
</div>
</template>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论