当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 详解vue2路由vue-router配置(懒加载)

详解vue2路由vue-router配置(懒加载)

2018年05月01日  | 移动技术网IT编程  | 我要评论

vue路由配置以及按需加载模块配置

1、首先在component文件目录下写俩组件:

first.vue:

<template> 
 <div>我是第一个页面</div> 
</template> 
 
<script> 
 export default { 
 name: 'first', 
 data () { 
  return { 
  msg: 'welcome to your vue.js app' 
  } 
 } 
 } 
</script> 
 
<!-- add "scoped" attribute to limit css to this component only --> 
<style scoped> 
 h1, h2 { 
 font-weight: normal; 
 } 
 
 ul { 
 list-style-type: none; 
 padding: 0; 
 } 
 
 li { 
 display: inline-block; 
 margin: 0 10px; 
 } 
 
 a { 
 color: #42b983; 
 } 
</style> 

second.vue:

<template> 
 <div>我是第二个页面</div> 
</template> 
 
<script> 
 export default { 
 name: 'second', 
 data () { 
  return { 
  msg: 'welcome to your vue.js app' 
  } 
 } 
 } 
</script> 
 
<!-- add "scoped" attribute to limit css to this component only --> 
<style scoped> 
 h1, h2 { 
 font-weight: normal; 
 } 
 
 ul { 
 list-style-type: none; 
 padding: 0; 
 } 
 
 li { 
 display: inline-block; 
 margin: 0 10px; 
 } 
 
 a { 
 color: #42b983; 
 } 
</style> 

2、router目录下的index.js文件配置路由信息:

import vue from 'vue' 
import vuerouter from 'vue-router' 
/*import first from '@/components/first' 
import second from '@/components/second'*/ 
 
vue.use(vuerouter) 
 
/*const routes = [ 
 //重定向 
 { 
 path:'/', 
 redirect:'first' 
 }, 
 { 
 path: '/first', 
 name: 'first', 
 component: first 
 }, 
 { 
 path: '/second', 
 name: 'second', 
 component: second 
 } 
]*/ 
 
//懒加载路由 
const routes = [ 
 {   //当首次进入页面时,页面没有显示任何组件;让页面一加载进来就默认显示first页面 
 path:'/', //重定向,就是给它重新指定一个方向,加载一个组件; 
 component:resolve => require(['@/components/first'],resolve) 
 }, 
 { 
 path:'/first', 
 component:resolve => require(['@/components/first'],resolve) 
 }, 
 { 
 path:'/second', 
 component: resolve => require(['@/components/second'],resolve) 
 } 
//这里require组件路径根据自己的配置引入 
] 
//最后创建router 对路由进行管理,它是由构造函数 new vuerouter() 创建,接受routes 参数。 
 
 const router = new vuerouter({ 
 routes 
}) 
 
export default router; 

3、main.js中引入路由配置文件:

import $ from 'jquery' 
import vue from 'vue' 
import app from './app' 
import router from './router' //引入路由配置文件 
import './assets/css/bootstrap.min.css' 
import './assets/js/bootstrap.min' 
vue.config.productiontip = false 
 
/* eslint-disable no-new */ 
new vue({ 
 el: '#app', 
 router, // 注入到根实例中 
 render: h => h(app) 
})

4、app.vue引入路由配置导航:

<template> 
<router-link to="/first">跳转第一个页面</router-link> 
<router-link to="/second">跳转第二个页面</router-link> 
<div id="view"> 
  <router-view></router-view> 
  </div> 
 
</template> 
 
<script> 
export default { 
 name: 'app' 
} 
</script> 
<style> 
</style> 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网