首页 > 编程 > JavaScript > 正文

Vue-Router基础学习笔记(小结)

2019-11-19 12:42:04
字体:
来源:转载
供稿:网友

vue-router是一个插件包,要先用npm进行安装

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]

解耦合

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表