javascript - 在菜单链接中使用 # ids 时,Vue Js 历史记录模式不会删除 #

标签 javascript vue.js url vue-router

我正在使用 Vue 和 VueRouter 组合一个 SPA。该网站运行正常,我可以单击链接并访问菜单项。我在 url 中看到 # 仍然位于链接名称之前。例如,如果我单击菜单中的服务,则 URL 状态为 https://sitename.com/#services 我正在使用模式:“历史”,它应该可以解决这个问题,但是我相信我错过了一些东西。如果有人可以查看我的代码并帮助我解决这个问题,我将不胜感激。谢谢。

在我的根目录中,我有 router.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

function load(componentName) {
    return () => import(`@/components/${componentName}`);
}

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Home',
            component: load('Home')
        }
        ,
        {
            path: '/services',
            name: 'Services',
            component: load('Services')
        },
        {
            path: '/portfolio',
            name: 'Portfolio',
            component: load('Portfolio')
        },
        {
            path: '/about',
            name: 'About',
            component: load('About')
        },
        {
            path: '/team',
            name: 'Team',
            component: load('Team')
        },
        {
            path: '/contact',
            name: 'Contact',
            component: load('Contact')
        },
        {
            path: '/privacy',
            name: 'Privacy',
            component: load('Privacy')
        },
        {
            path: '/success',
            name: 'Success',
            component: load('Success')
        }
    ]
});

export default router;

在我的源目录和组件中,我有 Nav.vue 组件 你可以看到我正在使用一个条件,表示 0 的索引是否为 # 等。我认为这应该消除散列,但事实并非如此。

导航.vue

<template>
  <div>
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav">
      <div class="container">
        <a class="navbar-brand js-scroll-trigger" href="/">
          <span class="first-r">R</span>
          <span class="second-r">R</span>
          <span class="spark">Spark</span>
        </a>
        <button
          class="navbar-toggler navbar-toggler-right"
          type="button"
          data-toggle="collapse"
          data-target="#navbarResponsive"
          aria-controls="navbarResponsive"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          Menu
          <i class="fas fa-bars"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav text-uppercase ml-auto">
            <li class="nav-item" v-for="(linkObj, ind) in navList" :key="ind">
              <a
                class="nav-link js-scroll-trigger"
                :href="linkObj.path"
                v-if="linkObj.path.indexOf('#') === 0"
              >{{linkObj.name}}</a>
              <router-link
                class="nav-link"
                js-scroll-trigger
                v-else
                :to="linkObj.path"
              >{{linkObj.name }}</router-link>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </div>
</template>
<script>
export default {
  data: () => ({
    navList: [
      {
        name: "Services",
        path: "#services"
      },
      {
        name: "Portfolio",
        path: "#portfolio"
      },
      {
        name: "About",
        path: "#about"
      },
      {
        name: "Team",
        path: "#team"
      },
      {
        name: "Contact",
        path: "#contact"
      }
    ]
  })
};
</script>
<style lang="">
</style>

在我的 App.vue 的 SRC 中

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

main.js

import Vue from 'vue';
import App from './App.vue';
import router from '../router';
import VueResource from "vue-resource"
import './assets/css/style.css'
import './assets/vendor/bootstrap/css/bootstrap.min.css';
import './assets/vendor/fontawesome-free/css/all.min.css';


Vue.config.productionTip = false
Vue.use(VueResource);


new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

由于篇幅原因,我只展示 Home.vue 组件的最小值

<template>
  <div>
    <Nav></Nav>
    <div>
      <header class="masthead">
        <div class="container">
          <div class="masthead-holder">
            <img src="../assets/img/RRLogo2.png" class="mt-5 logo" alt />
            <div class="intro-text">
              <div class="intro-lead-in">Welcome RR Spark Web Studio!</div>
              <div class="intro-heading text-uppercase">Hire Us For Your Next Web Project</div>
              <a
                class="btn tell-me btn-xl text-uppercase js-scroll-trigger"
                href="#services"
              >Tell Me More</a>
            </div>
          </div>
        </div>
      </header>
    </div>

    <div>
      <section class="page-section" id="services">
        <div class="container">
          <div class="row">
            <div class="col-lg-12 text-center">
              <h2 class="section-heading text-uppercase">Services</h2>
              <h3 class="section-subheading text-muted">Delivering your ideal website is what we do. 
              </h3>
            </div>
          </div>
          <div class="row text-center">
            <div class="col-md-4">
              <span class="fa-stack fa-4x">
                <i class="fas fa-circle fa-stack-2x icon-color"></i>
                <i class="fas fa-paint-brush fa-stack-1x fa-inverse"></i>
              </span>
              <h4 class="service-heading">Web Design</h4>
              <p
                class="text-muted text-justify"
              >We take the time to really know your company to get a better understanding of your goals, vision and where you want to go in order to create that perfect, unique website that will help you reach your specific target audience. Your site needs to be user friendly, functional and visually pleasing and that is where are designer comes in to ensure the design is exactly what you want.</p>
            </div>
            <div class="col-md-4">
              <span class="fa-stack fa-4x">
                <i class="fas fa-circle fa-stack-2x icon-color"></i>
                <i class="fas fa-globe fa-stack-1x fa-inverse"></i>
              </span>
              <h4 class="service-heading">Web Development</h4>
              <p
                class="text-muted text-justify"
              >Working hand in hand with our designer, we use the latest in web technology, such as HTML; CSS3; JavaScript, to bring you a site that is fast, SEO (Search Engine Optimization) friendly as well as highly responsive. Keeping up with the latest Standards from W3C, your project will be built for a superior user experience on mobile, tablet as well as PC.</p>
            </div>
            <div class="col-md-4">
              <span class="fa-stack fa-4x">
                <i class="fas fa-circle fa-stack-2x icon-color"></i>
                <i class="fas fa-laptop fa-stack-1x fa-inverse"></i>
              </span>
              <h4 class="service-heading">Content Management</h4>
              <p
                class="text-muted text-justify"
              >Keeping up with changes on your site in this fast-paced world means that your site will constantly need new and fresh content. Using a content management system (CMS), such as WordPress allows you, the user, the ability to quickly add new content whenever you wish, maintain and implement marketing campaigns and monitor analytics all from within the user dashboard. We provide either WordPress modifications or Custom theming solutions.</p>
            </div>
          </div>
          <div class="row mt-5">
            <div class="col-lg-12 text-center">
              <h2 class="section-heading text-uppercase">Ready? So Are We</h2>
              <div class="row">
                <div class="col-lg-6 p-5">
                  <h3
                    class="section-subheading text-muted mb-4"
                  >For a no-obligation quote, click the button below and tell us all about your project.</h3>
                  <a
                    class="btn tell-me btn-xl mt-0 mb-4 text-uppercase js-scroll-trigger"
                    href="#contact"
                  >CLICK ME</a>
                </div>
                <div class="col-lg-6 p-5">
                  <h3
                    class="section-subheading text-muted mb-4"
                  >If you don't like contact forms, ask us a question via WhatsApp using the button below.</h3>
                  <a
                    class="btn tell-me btn-xl mt-0 text-uppercase js-scroll-trigger"
                    href="https://api.whatsapp.com/send?phone=525517043338"
                    target="_blank"
                  >WhatsApp</a>
                </div>
              </div>
              <!--end row CTA-->
            </div>
          </div>
        </div>
      </section>
    </div>

<!--other sections-->



<div>
      <section class="page-section" id="contact">
        <div class="container">
          <div class="row">
            <div class="col-lg-12 text-center">
              <h2 class="section-heading text-uppercase">Contact Us</h2>
              <h3
                class="section-subheading text-white"
              >We are ready to get your project up and live.</h3>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-12">
              <Contact></Contact>
            </div>
          </div>
        </div>
      </section>
    </div>

    <Footer></Footer>
  </div>
</template>
<script>
import Nav from "./Nav";
import Footer from "./Footer";
import Contact from "./Contact";
export default {
  name: "App",
  components: {
    Nav,
    Contact,
    Footer
  },
  data: () => ({
    portfolioJSON: [
      {
        linkToModal: "#portfolioModal1",
        image: require("../assets/img/portfolio/icoimanismall.jpg"),
        header: "Imani Luz Y Harmonía",
        caption: "Graphic Design"
      },
      {
        linkToModal: "#portfolioModal2",
        image: require("../assets/img/portfolio/icopsicliliansmall.jpg"),
        header: "Transformando Vidas",
        caption: "Web Development"
      },
      {
        linkToModal: "#portfolioModal3",
        image: require("../assets/img/portfolio/icopsicovintsmall.jpg"),
        header: "Viaje a tu Interior",
        caption: "Web Development"
      },
      {
        linkToModal: "#portfolioModal4",
        image: require("../assets/img/portfolio/algovisolutionsthumb.png"),
        header: "Algovi Solutions Landing Page",
        caption: "Web Development"
      },
      {
        linkToModal: "#portfolioModal5",
        image: require("../assets/img/portfolio/naplesdentalthumb.png"),
        header: "Naples Dental Clinic",
        caption: "Web Development"
      },
      {
        linkToModal: "#portfolioModal6",
        image: require("../assets/img/portfolio/xploreflythumb.png"),
        header: "Xplorefly Travel Agency",
        caption: "Web Development"
      }
    ]
  })
};
</script>
<style lang="">
</style>

再次感谢您阅读本文,因为我是 VueJS 和学习的新手。

最佳答案

Nav.vue你的navList包含路径的数组有 # 。这些路径必须与您在 router.js 上定义的路径相同。尝试更改您的数组

来自:

navList: [
      {
        name: "Services",
        path: "#services"
      },
      {
        name: "Portfolio",
        path: "#portfolio"
      },
      {
        name: "About",
        path: "#about"
      },
      {
        name: "Team",
        path: "#team"
      },
      {
        name: "Contact",
        path: "#contact"
      }
    ]

navList: [
      {
        name: "Services",
        path: "/services"
      },
      {
        name: "Portfolio",
        path: "/portfolio"
      },
      {
        name: "About",
        path: "/about"
      },
      {
        name: "Team",
        path: "/team"
      },
      {
        name: "Contact",
        path: "/contact"
      }
    ]

如果您无法修改数组,请尝试修改字符串,例如:

<router-link :to="linkObj.path.replace('#','/')">{{ linkObj.name }}</router-link>

结论

用于路由导航来渲染 <router-view /> 中的其他组件标签,尝试使用独占 <router-link to="/path">标签。 <a href="/path">标签也会为您导航,但这会重新加载页面。

如果您想导航到页面中的 anchor ,您仍然可以使用 <a href="#anchorId">

关于javascript - 在菜单链接中使用 # ids 时,Vue Js 历史记录模式不会删除 #,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60665983/

相关文章:

java - 如何在java中获取url html内容到字符串

javascript - 如何使用 jQuery 格式化电话号码

javascript - 如果输入字段已预填充,则 jQuery 不起作用(切换清除功能)

javascript - 如何将多个 Axios 调用链接在一起,以便它们同步运行并且每个调用都可以使用前一个调用返回的数据

javascript - vue-属性-装饰器 : Prop being mutated?

javascript - 让 VueJS 接受动态图像字符串有问题

django - TastyPie - Override_urls 忽略身份验证和授权

php - 有什么东西不见了吗?在不刷新\重新加载页面的情况下更改\更新页面内容

javascript - 通过javascript或jquery访问iframe中的span

用于检索 url 的最后部分的 Excel 公式