Vue Router 路由器简介和使用

发布于 2022-07-29 12:42:38 字数 2774 浏览 225 评论 0

Vue Router 是 Vue 的官方路由器。 路由器的重点是将单页应用程序与浏览器导航集成在一起,例如后退按钮。

以下是使用 Vue Router 创建包含 2 个链接的页面的方法。 第一的, example1.html

<html>
  <head>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  </head>

  <body>
    <div></div>
    <script src="example1.js"></script>
  </body>
</html>

此脚本加载 example1.js,下面是 example1.js 文件:

const router = new VueRouter({
  routes: [
    // A route maps paths to components - when the portion of the URL after
    // '#' changes, Vue router changes which component is displayed
    {
      path: '/home',
      component: { template: '<h1>Home</h1>' }
    },
    {
      path: '/about',
      component: { template: '<h1>About Us</h1>' }
    }
  ]
});

const app = new Vue({
  router,
  // The `router-link` and `router-view` components are from Vue router.
  // `router-link` becomes an <a> that links to the correct path
  // `router-view` is where Vue router renders the component or template
  // that corresponds to the current path.
  template: `
    <div>
      <div>
        <router-link to="/home">Home</router-link>
        <router-link to="/about">About Us</router-link>
      </div>
      <div>
        <router-view></router-view>
      </div>
    </div>
  `
}).$mount('#content');

这是这个基本 Vue 路由器设置的实时示例

测试

很多方法可以测试 Vue 应用程序 。另一种方法是使用 Segment 的浏览器自动化工具 Nightmare 。这是 Mocha 我们用来测试本文示例

  describe('router', function() {
    it('basic example', async function() {
      const nightmare = new Nightmare({ show: false });

      await nightmare.
        goto(`file://${process.cwd()}https://masteringjs.io/tutorials/vue/router/example1.html`).
        wait('#rendered-content');

      await nightmare.click('a[href="#/home"]');
      let res = await nightmare.evaluate(() => document.querySelector('h1').innerHTML);
      assert.equal(res, 'Home');

      await nightmare.click('a[href="#/about"]');
      res = await nightmare.evaluate(() => document.querySelector('h1').innerHTML);
      assert.equal(res, 'About Us');

      await nightmare.end();
    });
  });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

0 文章
0 评论
22 人气
更多

推荐作者

策马西风

文章 0 评论 0

柠檬心

文章 0 评论 0

1331

文章 0 评论 0

七度光

文章 0 评论 0

qq_oc2LaO

文章 0 评论 0

野却迷人

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文