我試圖了解如何將事件從子組件發送到通過 ref 或 id 滾動到正確部分的父組件。例如,導航選單是一個帶有鏈接的子組件。當我單擊一個鏈接時,父級中的相應部分會滾動到視圖中。我來自 React,所以我有點被甩了。如何向上傳遞引數以滾動到正確的 ref 或 id?基本上錨鏈接的行為方式。
這是我到目前為止所得到的......我不確定我應該使用鏈接,我可能需要按鈕,因為我沒有導航頁面。
Navigation.vue(兒童)
<template>
<div >
<img alt="從 Vue.js 中的子組件滾動到部分" src="../assets/logo.png" />
<nav>
<ul>
<li>
<a @click="goSection" href="/">Contact</a>
</li>
<li>
<a href="/">Projects</a>
</li>
<li>
<a href="/">Skills</a>
</li>
<li>
<a href="/">Education</a>
</li>
</ul>
</nav>
</div>
</template>
<script>
export default {
name: "Navigation",
//I want to emit an event in the parent where the page section scrolls in to view//
methods: {
goSection() {
this.$emit("go-section", this.value);
},
},
};
</script>
應用程式.vue(父)
<template>
<div id="app">
<Navigation @go-section="goToSection" />
<section ref="projects">
<p>Projects</p>
</section>
<section ref="skills">
<p>Skills</p>
</section>
<section ref="contact">
<p>Contacts</p>
</section>
</div>
</template>
<script>
import Navigation from "./components/Navigation.vue";
export default {
name: "App",
components: {
Navigation,
},
methods: {
goToSection(event, value) {
var element = this.$refs[(event, value)];
var top = element.offsetTop;
window.scrollTo(0, top);
},
},
};
</script>
uj5u.com熱心網友回復:
您可以使用a標簽但阻止默認鏈接行為,并將 ref 傳遞給您的goSection方法:
Vue.component('navigation', {
template: `
<div >
<img alt="從 Vue.js 中的子組件滾動到部分" src="../assets/logo.png" />
<nav>
<ul>
<li>
<a @click.prevent="goSection('contact')" href="/">Contact</a>
</li>
<li>
<a href="#" @click.prevent="goSection('projects')">Projects</a>
</li>
<li>
<a href="#" @click.prevent="goSection('skils')">Skills</a>
</li>
<li>
<a href="#" @click.prevent="goSection('contact')">Education</a>
</li>
</ul>
</nav>
</div>
`,
methods: {
goSection(val) {
this.$emit("go-section", val);
},
},
})
new Vue({
el: '#demo',
methods: {
goToSection(value) {
const top = this.$refs[(value)].offsetTop;
window.scrollTo({
top: top,
left: 0,
behavior: 'smooth'
});
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<navigation @go-section="goToSection"></navigation>
<section class="section" ref="projects">
<p>Projects</p>
</section>
<section class="section" ref="skills">
<p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p><p>Skills</p>
</section>
<section class="section" ref="contact">
<p>Contacts</p>
</section>
</div>
uj5u.com熱心網友回復:
您可以在子組件中發出帶有引數的事件(例如 section ref):
<a @click="$emit('go-section', 'contact')" href="/">Contact</a>
<a @click="$emit('go-section', 'projects')" href="/">Projects</a>
然后在parent的listener方法中使用這個引數
// template
<Navigation @go-section="goToSection" />
// js
goToSection(sectionRef) {
var element = this.$refs[sectionRef];
var top = element.offsetTop;
window.scrollTo(0, top);
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/419958.html
標籤:
