Vue.js锚定到同一组件中的div [英] Vue.js anchor to div within the same component

查看:99
本文介绍了Vue.js锚定到同一组件中的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Vue.js应用程序,但无法将锚链接到组件中的某个div.

I'm developing a Vue.js application and I'm having trouble to link an anchor to a certain div within a component.

我有以下锚点:

<a href="#porto" class="porto-button">Porto, Portugal</a>

和以下div:

<div id="porto" class="fl-porto">

我在哈希模式下使用vue-router.

I'm using vue-router in hash mode.

问题是,每当我单击"porto-button"时,它将重定向到主页"页面('/')

The problem is, whenever I click the "porto-button" it will redirect me to the "home" page ( ' / ' )

我正在使用Vue.js 1.X,并尝试使用历史记录模式(不带哈希键的URL),但刷新页面后出现cannot GET '/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?

推荐答案

由于您在哈希模式下使用路由器,因此无法轻松滚动,因为滚动到/#something实际上会将您重定向到某物"页面

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);
  }
}

工作原理:

  1. 通过ref属性设置对要滚动到的元素的引用;
  2. 编写一个函数,该函数将以编程方式将window.scrollY设置为所引用元素的top.
  3. 工作已完成:)
  1. Set the references through ref attribute to the element you would like to scroll to;
  2. Write a function that will programmatically set window.scrollY to the top of the referenced element.
  3. Job is done :)

更新1:

jsfiddle https://jsfiddle.net/5k4ptmqg/4/

jsfiddle https://jsfiddle.net/5k4ptmqg/4/

更新2:

似乎在Vue 1中ref="name"看起来像el:name (文档),这是一个更新的示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆