Vue.js 路由和 JQuery - 从路由返回

Vue.js routing and JQuery - coming back from a route

有一个问题(我正在使用 vue-router 并以正确的方式配置路由):我有一个主页(组件 home.vue)并使用 jquery 代码:单击一个按钮后,它向下滚动到某个 div(它工作正常),我有另一个按钮可以路由到不同的组件。路由有效,但从路由返回后(组件 newpage.vue 中有一个按钮),主页上的 jquery 代码(滚动)不再起作用。我的 jquery 代码的其余部分工作正常。

App.vue(主要成分):

<template>
    <div>
      <router-view></router-view>
    </div>
</template>

路由路径:

export const routes = [
  { path: '', component: Home },
  { path: '/newpage', component: Newpage}
];

主页:(home.vue 组件)

   <div>
      //scrolling button
      <a href="#scroll"><button type="button">scroll</button></a>
      <div id="scroll"></div>
      //route - new component name is 'newpage'
      <router-link :to="'newpage'" tag="button">component</router-link>
   </div>

组件'newpage':

<div>
     <router-link :to="'/'" tag="button">Home</router-link>
</div>

滚动代码:

$(function () {
  $('a[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

      if (target.length) {
        $('html,body').animate({
          scrollTop: (target.offset().top)
        }, 1500, 'easeInOutQuart');

        return false;
      }
    }
  });
});

我该怎么做才能让它发挥作用?

您可能需要事件委托:

$(document).on('click', 'a[href*=#]:not([href=#])', function () {
    // ...the rest of your code
});

原因是您尝试绑定的元素在页面更改时被删除,并在更改回来后添加。事件委托通过允许事件冒泡并附加到静态的东西来解决这个问题。

但是,出于性能原因,最好将委托事件绑定到更近的静态元素,例如 #app.