Vue.js 锚定到同一组件内的 div [英] Vue.js anchor to div within the same component
问题描述
我正在开发 Vue.js 应用程序,但无法将锚点链接到组件内的某个 div.
我有以下锚点:
葡萄牙波尔图</a>
以及以下 div:
我在哈希模式下使用 vue-router.
问题是,每当我单击porto-button"时,它都会将我重定向到主页"页面('/')
我使用的是 Vue.js 1.X,我尝试使用历史模式(不带 hashbang 的 URL),但它在刷新页面时给我一个 cannot GET '/page'
错误.
我做错了吗?我该怎么办?
解决方案 因为你在散列模式下使用路由器,你将无法轻松滚动,因为滚动到 /#something
实际上会将您重定向到某事"页面.
你必须自己模拟滚动行为,尝试做这样的事情:
//P.S.代码是为 Vue 2 编写的.//您必须将其调整为 Vue 1.//你的观点:<a class="porto-button" @click="scrollMeTo('porto')">葡萄牙波尔图</a>...<div ref="porto" class="fl-porto">
//您的代码:方法: {scrollMeTo(refName) {var element = this.$refs[refName];var top = element.offsetTop;window.scrollTo(0, top);}}
工作原理:
- 通过
ref
属性将引用设置为要滚动到的元素; - 编写一个函数,以编程方式将
window.scrollY
设置为引用元素的 top
. - 工作完成了:)
更新 1:
jsfiddle https://jsfiddle.net/5k4ptmqg/4/
更新 2:
似乎在 Vue 1 ref="name"
看起来像 el:name
(docs),这是一个更新的例子:
https://jsfiddle.net/5y3pkoyz/2/
I'm developing a Vue.js application and I'm having trouble to link an anchor to a certain div within a component.
I have the following anchor:
<a href="#porto" class="porto-button">Porto, Portugal</a>
and the following div:
<div id="porto" class="fl-porto">
I'm using vue-router in hash mode.
The problem is, whenever I click the "porto-button" it will redirect me to the "home" page ( ' / ' )
I'm using Vue.js 1.X and I tried using history mode (URL without the hashbang) but it gives me a cannot GET '/page'
error upon refreshing a page.
Am I doing something wrong? What can I do about this?
解决方案 Because you are using router in hash mode, you will not be able to scroll that easily because scrolling to /#something
will actually redirect you to 'something' page.
You will have to emulate scrolling behaviour on your own, try doing something like that:
//P.S. the code is written for Vue 2.
//You will have to adjust it to Vue 1.
//Your view:
<a class="porto-button" @click="scrollMeTo('porto')">Porto, Portugal</a>
...
<div ref="porto" class="fl-porto">
//Your code:
methods: {
scrollMeTo(refName) {
var element = this.$refs[refName];
var top = element.offsetTop;
window.scrollTo(0, top);
}
}
How it works:
- Set the references through
ref
attribute to the element you would like to scroll to;
- Write a function that will programmatically set
window.scrollY
to the top
of the referenced element.
- Job is done :)
Update 1:
jsfiddle https://jsfiddle.net/5k4ptmqg/4/
Update 2:
Seems that in Vue 1 ref="name"
looked like el:name
(docs), here is an updated example:
https://jsfiddle.net/5y3pkoyz/2/
这篇关于Vue.js 锚定到同一组件内的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文