博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue-Router基础学习笔记
阅读量:6924 次
发布时间:2019-06-27

本文共 3859 字,大约阅读时间需要 12 分钟。

1、安装vue-router

npm install vue-routeryarn add vue-router

2、引入注册vue-router

import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)

3、链接跳转

<router-link to='/home'></router-link>    //你可以在template中使用它实现一个可点击跳转到home.vue的 a 标签this.$router.push('/about');    //在methods方法中跳转到about页面this.$router.go('-1');    //在js中返回上一个页面

4、经常用到

this.$route.params.name    //在js中获取路由的参数.router-link-active    //当前选中路由的匹配样式$route.query    //获取查询参数$route.hash    //哈希

5、路由配置

export default new Router({    routes:[        {                //第一层是顶层路由,顶层路由中的router-view中显示被router-link选中的子路由            path:'/',            name:'Home',            component:'Home'        },{            path:'/user/:id',    //www.xxx.com/user/cai            name:'user',    //:id是动态路径参数            component:'user',            children:[                {                    path:'userInfo',    //www.xxx.com/user/cai/userInfo                    component:'userInfo'    //子路由将渲染到父组件的router-view中                },{                    path:'posts',                    component:'posts'                }            ]        }    ]})Vue.use(Router);

6、路由参数方式变化时,重新发出请求并更新数据

//比如:用户一切换到用户二, 路由参数改变了,但组件是同一个,会被复用// 从 /user/cai 切到 /user/wan在User组件中://方法1:    watch:{        '$route'(to,from){            //做点什么,比如:更新数据        }    }//方法二:    beforeRouteUpdate(to,from,next){        //同上    }

7、编程式导航

router.push({name:'user',params:{userId:'123'}})    //命名路由导航到user组件<router-link :to='{name:'user',params:{userId:'123'}}'>用户</router-link>router.push({path:'register',query:{plan:'cai'}})    //query查询参数router.push({path:`/user/${userId}`})    //queryrouter.push(location,onComplete,onAbort)router.replace()    //替换router.go(-1)

8、命名视图

//当前组件中只有一个 router-view 时,子组件默认渲染到这里<router-view class='default'></router-view><router-view class='a' name='left'></router-view><router-view class='b' name='main'></router-view>routes:[    {        path:'/',        components:{            default:header,            left:nav,            main:content    //content组件会渲染在name为main的router-view中        }    }]//嵌套命名视图就是:子路由+命名视图

9、重定向与别名

const router = new VueRouter({    routes: [        { path: '/a', redirect: '/b' },        { path: '/b', redirect: { name: 'foo' }},    //命名路由方式        { path: '/c', redirect: to => {    //动态返回重定向目标          // 方法接收 目标路由 作为参数          // return 重定向的 字符串路径/路径对象        }}    ]})const router = new VueRouter({    routes: [        { path: '/a', component: A, alias: '/b' }    //别名:当访问 /b 时也会使用A组件    ]})

10、路由组件传参

const User={    props:['id'],    template:`<div>{
{id}}</div>`}const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, props: true }, // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项: { path: '/user/:id', components: { default: User, sidebar: Sidebar }, props: { default: true, sidebar: false } } ]})

11、HTML5的History模式下服务端配置

const router = new VueRouter({    mode: 'history',    routes: [        { path: '*', component: 404}    ]})后端配置://Nginx    location / {      try_files $uri $uri/ /index.html;    }    //Apache    <IfModule mod_rewrite.c>      RewriteEngine On      RewriteBase /      RewriteRule ^index\.html$ - [L]      RewriteCond %{REQUEST_FILENAME} !-f      RewriteCond %{REQUEST_FILENAME} !-d      RewriteRule . /index.html [L]    </IfModule>//Node.js    const http = require('http')    const fs = require('fs')    const httpPort = 80    http.createServer((req, res) => {      fs.readFile('index.htm', 'utf-8', (err, content) => {        if (err) {          console.log('无法打开index.htm页面.')        }        res.writeHead(200, {          'Content-Type': 'text/html; charset=utf-8'        })        res.end(content)      })    }).listen(httpPort, () => {      console.log('打开: http://localhost:%s', httpPort)    })    //使用了Node.js的Express    [使用中间件][1]

推荐文章:

原文地址:

转载地址:http://lfjjl.baihongyu.com/

你可能感兴趣的文章
PostgreSQL中的简单压缩算法
查看>>
Asp之IIS 6.0搭建篇
查看>>
《Spring Boot系列》- 统一异常处理
查看>>
最详细的Log4j使用教程
查看>>
EventBus的使用以及学习心得
查看>>
Android Activity的Launch Mode
查看>>
Java内嵌Groovy脚本引擎进行业务规则剥离(四)--Groovy规则化脚本整合至JAVA
查看>>
AWS 使用 CodeBuild 进行云端构建
查看>>
0. SpringBoot --引言
查看>>
《大话数据结构》读书笔记系列(二)---- 算法
查看>>
JSTL 核心标签库 使用
查看>>
解决Rockmongo不显示中文的问题
查看>>
asp.net core 自定义使用MemoryCache
查看>>
fedora下/etc/sysconfig/network-scripts/ifcfg-eth0配置
查看>>
spring boot 的application.yml配置
查看>>
正则表达式与sed工具
查看>>
Twemproxy和Redis性能压力测试
查看>>
EXCEL汇总文件信息
查看>>
Vmware vSphere 5.0系列教程之一 Vmware vSphere 5.0简介
查看>>
使用 OpenSSL API 进行安全编程
查看>>