美文网首页
Vue学习笔记[14]-vue-router使用动态路由&路由懒

Vue学习笔记[14]-vue-router使用动态路由&路由懒

作者: 神楽花菜 | 来源:发表于2019-11-23 14:24 被阅读0次

动态路由

在某些情况下,一个页面的path可能是不固定的例如/user/1561361这时候可以使用:to="'' "动态路由:

  • 创建user的vue组件
    可通过$route.params.userID来获取url中的参数
<template>
  <div>
      <h2>user:{{userID}}</h2>
  </div>
</template>

<script>
export default {
  name:'User',
computed: {
    userID() {
        return this.$route.params.userID 
    }
},
};
</script>

<style scoped>

</style>
  • index.js配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'

Vue.use(VueRouter)

const routes = [
//... 
  {
    path:'/user/:userID', // 使用:userID来传递参数
    component:User
  }
]
  • app.js显示User组件
<router-link :to="'/user/'+userID" tag='button'> USER </router-link>
//...
 <script>
export default {
  name: "App",
  data() {
    return {
      userID: 5050
    }
  },
}
</script>

路由懒加载

若不使用路由懒加载,那么所有的组件都会打包到app.js中,久而久之会使得app.js变得十分庞大。
如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候在加载对应的组件,这样就更加高效了。


未使用懒加载的js打包后结构
import Vue from 'vue'
import VueRouter from 'vue-router'
const Home = ()=>import('../components/Home')
const About = ()=>import('../components/About')
const User = ()=>import ('../components/User')

Vue.use(VueRouter)

const routes = [
  {
    path:'',
    redirect:'/home'
  },

  {
    path:'/home',
    component: Home
  },

  {
    path:'/about',
    component:About
  },

  {
    path:'/user/:userID',
    component:User
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

使用懒加载

.map文件是丑化后的js到原js的映射。如果您正确设置了源映射,则应该在“ source”选项卡的文件窗格中看到列出的每个原始JavaScript文件。

The Sources Tab in Chrome Dev Tools
更多参考:introduction-source-maps

相关文章

网友评论

      本文标题:Vue学习笔记[14]-vue-router使用动态路由&路由懒

      本文链接:https://www.haomeiwen.com/subject/hzacwctx.html