【问题标题】:Vue.js routing and JQuery - coming back from a routeVue.js 路由和 JQuery - 从路由返回
【发布时间】:2018-06-17 20:00:48
【问题描述】:

有一个问题(我正在使用 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>

组件“新页面”:

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

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

【问题讨论】:

    标签: jquery scroll vue.js vue-router


    【解决方案1】:

    您可能需要事件委托:

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

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

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

    【讨论】:

    • -1。小心解释为什么?你躲在你的反对票后面并没有帮助任何人。
    猜你喜欢
    • 2020-10-17
    • 2015-12-23
    • 2022-07-24
    • 2018-09-18
    • 2019-01-16
    • 1970-01-01
    • 2017-04-15
    • 2017-11-17
    • 2017-09-24
    相关资源
    最近更新 更多