Description

The article for vue router.

Original post link:https://www.cnblogs.com/markjiang7m2/p/10796020.html

Source code:https://gitee.com/Sevenm2/Vue.Web/tree/master/Vue.Router

Start

Actually we should only remember 3 points for vue router.

  1. <router-link>. For user to click.
  2. <router-view>. To show the related content.
  3. router index.js. Declare which content will be show when user click a link.

<router-link> & <router-view> is a pair of tags for vue router. They are always used together.

router-link

<router-link> will be compiled into <a> when we build the project.

There is an important property to in <router-link>. It will tell the website which path will be redirected to when user click this link.

Html in App.vue

<ul>
<li><router-link to="/" >Home</router-link></li>
<li><router-link to="/food" >Food</router-link></li>
<li><router-link to="/rating">Rating</router-link></li>
<li><router-link to="/seller">Seller</router-link></li>
</ul>

It shows that when user click the Home link, the website will redirect to path /, and Food link for path /food, the same as Rating, Seller.

Actually it will be compiled as below.

<ul>
<li><a href="#/" >Home</a></li>
<li><a href="#/food" >Food</a></li>
<li><a href="#/rating">Rating</a></li>
<li><a href="#/seller">Seller</a></li>
</ul>

router-view

When website redirect to a path, such as /food, we may want to show something different in somewhere in the page. So we should add the <router-view> tag to the place which we want to show the related content.

Html in App.vue

<ul>
<li><router-link to="/" >Home</router-link></li>
<li><router-link to="/food" >Food</router-link></li>
<li><router-link to="/rating">Rating</router-link></li>
<li><router-link to="/seller">Seller</router-link></li>
</ul>
<router-view></router-view>

So if the related content is <div>Food content</div>, it will show in html as below.

<ul>
<li><a href="#/" >Home</a></li>
<li><a href="#/food" >Food</a></li>
<li><a href="#/rating">Rating</a></li>
<li><a href="#/seller">Seller</a></li>
</ul>
<div>Food content</div>

router index.js

As above, we say that <router-view> tag will be replaced by the related content, but what is the related content?

The route rule will be declared in the router index.js file. We can find this file in the path src\router\index.js as below.

In the index.js file, I have declared the rule.

import Vue from 'vue'
import Router from 'vue-router' Vue.use(Router) export default new Router({
routes: [
{
path: '/food',
component: { template: '<div>Food content</div>' }
},
{
path: '/seller',
component: { template: '<div>Seller content</div>' }
},
{
path: '/rating',
component: { template: '<div>Rating content</div>' }
}
]
})

As above, path /food related content is <div>Food content</div>.

The result will be shown as below.

Path /

We can see that the tag <router-view> is replaced as empty currently.



Path /food

We can see that the tag <router-view> is replaced by <div>Food content</div> currently.



In our actual development, we always have a lot of content to show in the tag <router-view>, so vue support to declare an individual component.

food.vue

<template>
<div class="content">
<div>Food content</div>
<!-- more other contents -->
</div>
</template> <script>
export default {
name: 'food',
data () {
return {
msg: 'food'
}
}
}
</script>

And then we can import these components in router index.js

import Vue from 'vue'
import Router from 'vue-router'
import food from '@/components/food'
import seller from '@/components/seller'
import rating from '@/components/rating' Vue.use(Router) export default new Router({
routes: [
{
path: '/food',
component: food
},
{
path: '/seller',
component: seller
},
{
path: '/rating',
component: rating
}
]
})

Dynamic Route Matching

Based on the above 3 route points, we can do some more extensions.

If our different paths are based on a parameter, such as an id, we can use a colon : to declare just one route in the index.js

import Vue from 'vue'
import Router from 'vue-router'
import food from '@/components/food' Vue.use(Router) export default new Router({
routes: [
{
path: '/:id',
name: 'food',
component: food
}
]
})

And in the component, we can use this.$route.params to get the parameter's value.

<template>
<div class="content">
<div>{{$route.params.id}} content</div>
</div>
</template> <script> export default {
name: 'food',
data () {
return {
msg: this.$route.params.id
}
}
}
</script>

Nested Routes

Sometimes, we may want to show some differences with different path based on food component. Then we should use the nested routes.

Firstly, I add a subfood component with a parameter.

<template>
<div class="subcontent">
<div>Sub Food content</div>
<div>{{$route.params.id}}</div>
</div>
</template> <script>
export default {
name: 'subfood',
data () {
return {
msg: 'subfood'
}
}
}
</script>

Secondly, we add links in food component, so that we can visit the subfood component.

<div>Food content</div>
<div class="subnavbar">
<ul>
<li><router-link to="/food/subfood1">SubFood1</router-link></li>
<li><router-link to="/food/subfood2">SubFood2</router-link></li>
<li><router-link to="/food/subfood3">SubFood3</router-link></li>
</ul>
<router-view></router-view>
</div>

And in the router index.js, we should a children property in /food section.

{
path: '/food',
component: food,
children:[
{
path: '/food/:id',
component: subfood
}
]
}

The result is as below.

In this case, maybe some of you will think that as the subfood path includ /food, so its content will show in food component's <router-view>.

However, all results are because of the router index.js declaration. We can make an example as below.

Delcare the subfood path in root.

{
path: '/food',
name: 'food',
component: food
},
{
path: '/seller',
name: 'seller',
component: seller
},
{
path: '/rating',
name: 'rating',
component: rating
},
{
path: '/food/:id',
name: 'subfood',
component: subfood
}

We can see that the subfood component is shown in the root's <router-view>.

The sub component will be shown in its parent component's <router-view>. If the component path is declared in root, it will be shown in the root's <router-view>

Named Routes

We can add a name property in router index.js.

{
path: '/food',
name: 'food',
component: food,
children:[
{
path: '/food/:id',
name: 'subfood',
component: subfood
}
]
}

Then we can use the named routes in <router-link>. Remember, we should a colon : before to property.

The below syntax are the same result.

<li><router-link :to="{name: 'food'}" >Food</router-link></li>
<li><router-link to="/food" >Food</router-link></li>

If there is an parameter in the path.

<li><router-link :to="{ name: 'food', params: { id: subfood1 }}" >Food</router-link></li>

Named Views

Sometimes we need to show multiple contents in the same time. Then we should add a name property for different </router-view>.

Firstly, I add a subextend component.

<template>
<div class="subcontent">
<div>Sub Extend content</div>
<div>{{$route.params.id}}</div>
</div>
</template> <script>
export default {
name: 'subextend',
data () {
return {
msg: 'subextend'
}
}
}
</script>

Secondly, add a </router-view> in food component.

<div class="subnavbar">
<ul>
<li><router-link to="/food/subfood1">SubFood1</router-link></li>
<li><router-link to="/food/subfood2">SubFood2</router-link></li>
<li><router-link to="/food/subfood3">SubFood3</router-link></li>
</ul>
<router-view></router-view>
<router-view name="ex"></router-view>
</div>

The next is router index.js. As there are multiple components, we should use property components, pls. noted the s.

The default component will be shown in </router-view> without name property and the ex component will be shown in </router-view> with name property value as "ex".

{
path: '/food',
name: 'food',
component: food,
children:[
{
path: '/food/:id',
name: 'subfood',
components: {
default: subfood,
ex: subextend
}
}
]
}

The result is as below.

Redirect in js

Sometimes we should do some logic judgement in js and then we could determine which path we could redirect to. We can use this.$router.push() to do this in js.

this.$router.push({ name: 'food', params: { id: "subfood1" }});
this.$router.push("/food/subfood1");

404 Error Page

When user want to access a Url which is not nonexistent, then we should redirect to a 404 page.

First, we add a 404 component.

<template>
<div class="content">
<div>404 Error</div>
</div>
</template> <script> export default {
name: 'error404',
data () {
return {
msg: '404'
}
}
}
</script>

Then add the route in router index.js. As we should catch all unknown Url, we should declare the route in root.

export default new Router({
routes: [
{
path: '*',
name: 'error404',
component: error404
},
{
path: '/food',
name: 'food',
component: food
}
...
]
})

Then we run the application and have a look.

We will find that when we access the root path, we get a 404 view. It is not the result we want.

It is because we donot declare the root view in router index.js. Let me to add it.

I add a home component and then declare it as the root view.

export default new Router({
routes: [
{
path: '*',
name: 'error404',
component: error404
},
{
path: '/',
name: 'home',
component: home
},
{
path: '/food',
name: 'food',
component: food
}
...
]
})

Then have a look.

It shows correctly now. When we access an unknown Url, the website will show the 404 view.

Maybe someone will say why the page will still show the menu in top. We should know that the elements in App.vue will always be shown. If we just want to show 404 view when we access an unknown page, we should move the menu elements into home component, and declare the menu components as children in home path.

home.vue

<template>
<div class="content">
<header>
<nav class='navbar'>
<ul>
<li><router-link to="/" >Home</router-link></li>
<li><router-link to="/food" >Food</router-link></li>
<li><router-link to="/rating">Rating</router-link></li>
<li><router-link to="/seller">Seller</router-link></li>
</ul>
<router-view></router-view>
</nav>
</header>
</div>
</template> <script> export default {
name: 'home',
data () {
return {
msg: 'home'
}
}
}
</script>

router index.js

{
path: '/',
name: 'home',
component: home,
children:[
{
path: '/food',
name: 'food',
component: food,
children:[
{
path: '/food/:id',
name: 'subfood',
components: {
default: subfood,
ex: subextend
}
}
]
},
...
]
}

Then the website will only show 404 view when we access an unknown Url.

Alias

As above, when we access the root path, it shows nothing in the RouterView. Actually sometimes we should show something, such as dashboard in the root path. How can we do this?

There is a property Alias in router. More uage description can be found in Vue.

Here we could only focus on the definition.

An alias of /a as /b means when the user visits /b, the URL remains /b, but it will be matched as if the user is visiting /a.

We know that a path begin with / means an absolute path, without / means a relative path. So we can declare a child in home view and set alias as '' or /. It means when we access /, we are actually accessing /food.

{
path: '/',
name: 'home',
component: home,
children:[
{
path: '/food',
name: 'food',
alias: '/',
component: food,
children:[
{
path: '/food/:id',
name: 'subfood',
components: {
default: subfood,
ex: subextend
}
}
]
},
...
]
}

HTML5 History Mode

Maybe you have found that all our Urls are including #. It's not a good link with #. Is there any way to remove this char? Sure. The HTML5 History Mode will help us. More uage description can be found in Vue.

We can set mode value as history in router index.js and then run the application. We can get a Url without #.

export default new Router({
mode: 'history',
routes: [
...
]
})

Build Setup command line

# install dependencies
npm install # serve with hot reload at localhost:8080
npm run dev # build for production with minification
npm run build # build for production and view the bundle analyzer report
npm run build --report # run unit tests
npm run unit # run e2e tests
npm run e2e # run all tests
npm test

Vue Study [2]: Vue Router的更多相关文章

  1. Vue Study [1]: Vue Setup

    Description The article for vue.js Setup. Original post link:https://www.cnblogs.com/markjiang7m2/p/ ...

  2. Vue 2.0 + Vue Router + Vuex

    用 Vue.js 2.x 与相配套的 Vue Router.Vuex 搭建了一个最基本的后台管理系统的骨架. 当然先要安装 node.js(包括了 npm).vue-cli 项目结构如图所示: ass ...

  3. vue教程3-05 vue组件数据传递、父子组件数据获取,slot,router路由

    vue教程3-05 vue组件数据传递 一.vue默认情况下,子组件也没法访问父组件数据 <!DOCTYPE html> <html lang="en"> ...

  4. Vue04——vue自定义事件、Router、Vue-cli、发布上线

    一.Vue的自定义事件 点击任何一个按钮,按钮本身计数累加,但是每点击三个按钮中的一个,totalCounter 都要累加. <body> <div id="app&quo ...

  5. vue & this.$route & this.$router

    vue & this.\(route & this.\)router const User = { template: '<div>User</div>' } ...

  6. Vue学习笔记-Vue.js-2.X 学习(七)===>脚手架Vue-CLI(路由Router)

    脚手架Vue-CLI(路由Router) 一 按装(通过新创建脚手架按装),如果在原来的脚手架上按装直接进图型化界面vue ui的插件按装. 二 使用(上面按装下面步骤自动会生成) 第一步:导入路由对 ...

  7. 浅谈 vue实例 和 vue组件

    vue实例: import Vue from 'vue'; import app from './app'; import myRouter from './routers'; new Vue({ e ...

  8. 【实战】Vue全家桶(vue + axios + vue-router + vuex)搭建移动端H5项目

    使用Vue全家桶开发移动端页面. 本博文默认已安装node.js. github链接 一.准备工作 安装vue npm install vue 安装脚手架vue-cli npm install -g ...

  9. js 引入Vue.js实现vue效果

    拆分组件为单个js见:https://www.jianshu.com/p/2f0335818ceb 效果 html <!DOCTYPE html> <html> <hea ...

随机推荐

  1. Python内置函数:strip()

    文章转载于:http://www.cnblogs.com/itdyb/p/5046472.html(博主:波比12) 在python API中这样解释strip()函数:

  2. Django基础(四)

    Form表单 Admin     Django Form表单 django 中的form 一般有两种功能: 输入html 验证用户输入 1,先写一个form import re from django ...

  3. linux串口基本编程

    Linux的串口表现为设备文件.Linux的串口设备文件命名一般为/dev/ttySn(n=0.1.2„„),若串口是USB扩展的,则串口设备文件命名多为/dev/ttyUSBn(n=0.1.2„„) ...

  4. Java学习之系统高可用性渲染接口日志自动服务降级

    背景:公司都追求系统的高可用性,这里不可用时间就是其中很重要的一个指标,为此在做系统功能升级迭代的过程中如何快速处理异常恢复正常功能极为重要.现在对新增模块的要求是都增加开关,方便快速关闭异常模块,但 ...

  5. 基于RFC5321使用ncat发送邮件

    今天和同事学习到的这个方法,学习了,记录一下: [root@localhost ~]# ncat TeamServer.localdomain ESMTP Postfix EHLO l00.win - ...

  6. 问题:Oracle出发器;结果:1、Oracle触发器详解,2、Oracle触发器示例

    ORACLE触发器详解 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创 ...

  7. 部署和调优 3.2 dns安装配置-2

    配置一个自定义的域,随便定义的,不实际存在. 在配置文件里,增加一个域 vim /etc/named.conf zone "123.com" IN { type master; f ...

  8. C#操作JSON专题

    第一章:C#如何拿到从http上返回JSON数据? 第二章:C#如何解析JSON数据?(反序列化对象) 第三章:C#如何生成JSON字符串?(序列化对象) 第四章:C#如何生成JSON字符串提交给接口 ...

  9. C#windows窗体应用程序如何自适应大小

    用C#的windows窗体应用程序做界面十分轻松,但是系统默认是没有让控件跟随窗体的大小改变而已改变的.所以需要我们手动去设置让窗体控件随着窗体的大小改变而改变.所以我们只需要将控件选择 然后把Anc ...

  10. Codeforces 1137C Museums Tour (强连通分量, DP)

    题意和思路看这篇博客就行了:https://www.cnblogs.com/cjyyb/p/10507937.html 有个问题需要注意:对于每个scc,只需要考虑进入这个scc的时间即可,其实和从哪 ...