vue中使用router

时间:2019-04-19
本文章向大家介绍vue中使用router,主要包括vue中使用router使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

router.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 这里面负责写路由映射,便于管理
// 创建路由实例并配置路由映射
// path:'*',redirect:'/home'  重定向到path是/home的映射 */
const router = new VueRouter({
  routes: [
	 {
      path: '/login',
      components: require('../pages/login/index.vue') // 这儿有两种写法  component: () => import('../pages/login/index.vue')   或者  components: require('../pages/login/index.vue')
    },
    {
      path: '/hello',
      components: require('../components/hello.vue') 
    },
    {
      path: '/404',
      component: () => import('../components/404.vue')  
    },
    {
      path: '*',
      redirect: '/login '
    }
  ]
})
export default router

login.vue

<template>
    <div>
      <h1>{{ msg }}</h1>
    </div>
</template>

<script>
export default {
  name: 'login',
  data () {
    return {
      msg: 'login'
    }
  }
}
</script>

<style scoped>

</style>

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import router from './router'
// 路由模块
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.use(ElementUI, { size: 'small' })
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  render: h => h(App)
})

效果图