Vue Router 路由器简介和使用
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 应用程序 。另一种方法是使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论