url中路由是改變的,可是改變路由公用一個組件javascript
舉例:前端
頁面中的配置:vue
<router-link class="nav-link " active-class='active' href="#" :to="{name:'detail',params:{id:'001'},query:{a:1,b:1}}" //在router-link標籤裏面設置 >數碼</router-link>
路由配置(這裏是二級路由)java
{ path: '/category', component: Category, children: [{ path: 'detail/:id', //:id表示能夠匹配/category後的全部參數, //舉例:http:localhost:8080/category/001?a=1&b=2hash=3 那麼:id就表明001開始日後的部分 component: Detail, name: 'detail' //這裏是命名路由 }] },
注意:因爲動態路由url中會攜帶參數 能夠用於發送數據請求 來獲取對應的數據webpack
那麼在組件中如何獲取url中攜帶的參數?ios
在vue生命週期created中來獲取數據 在vue的實例對象中存在$router裏面的params,query屬性就是url中的值web
<template> <div> <p>id:{{$route.params.id}}</p> <p>query.a:{{$route.query.a}}</p> <p>query.b:{{$route.query.b}}</p> </div> </template> <script> export default { created(){ console.log(this) } } </script>
案例:ajax
獲取堆糖網站上的信息渲染到頁面vue-router
首先在項目中建立vue.config.js (用來作前端的反向代理)axios
module.exports = { devServe: { proxy: { '/napi': { target: 'https://m.duitang.com', changeOrigin: true } } } }
利用axios請求網站上的數據(注意引入axios組件)
如今入口文件設置全局axios
import axios from 'axios' Vue.prototype.$http = axios
<script> export default { data(){ return { navs:null } }, created(){ this.$http({ url:'/napi/category/detail/', params:{ app_version:14, app_code:'mdt', category_id:'5017d172705cbe10c0000007', } }).then(res => { //將請求得來的數據 賦值給 當前組件的navs this.navs = res.data.data.sube_cates }) .catch(error => console.log(error)) } } </script>
最後在zxh上接受數據渲染到頁面
<template> <div> <ul> <li v-for = " list in lists " :key = "list.id"> <p> 點贊量:{{ list.favorite_count }} </p> \\隨便取數據渲染到頁面 <p> msg: {{ list.msg }} </p> </li> </ul> </div> </template> <script> export default { data () { return { lists: null } }, watch: { $route () { this.ajax() } }, methods: { ajax () { this.$http({ url: '/napi/blog/list/by_category/', params: { start: 0, include_fields: 'sender,album,like_count,msg', limit: 24, cate_key: this.$route.params.id, path: this.$route.query.path, _: Date.now() } }).then( res => { this.lists = res.data.data.object_list }) .catch( error => console.log( error )) } } } </script>
因爲每次點擊都至關於發起一次請求 極大增長了瀏覽器的性能,因此須要使用懶加載來減小請求的次數
在路由配置文件中設置
const Home = () => import(/* webpackChunkName: "group-foo" */ '../pages/Home.vue')
這種形式的導入模塊方式就是路由懶加載