vue路由入门

vue-router用于实现页面的跳转,例如点击Home按钮,进入Home页面,点击About按钮,进入About页面

一、基本路由

1.在src中新建两个vue文件,分别为home.vue和about.vue







2.在App.vue中定义


3.在index.js中定义路由,一组路由包含path和component两部分,vue通过比对path,跳转到相应的component

import Vue from 'vue'
import Router from 'vue-router'

import home from '../components/home.vue'
import about from '../components/about.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/home',
      component: home,
    },
    {
      path: '/about',
      component: about
    }
  ]
})

4.把路由注入到根实例

import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})

5.redirect 定义重定向,首次进入页面路径是'/',页面没有显示任何内容,使用重定向能使页面首次加载就会显示home页面

export default new Router({
  routes: [
    {
      path: '/home',
      component: home,
    },
    {
      path: '/about',
      component: about
    },
    {
      path: '/',
      redirect: '/home'
    }
  ]
})

二、动态路由

1.在App.vue添加两个

      User123
      User456

2.在index.js中配置动态路由

export default new Router({
  routes: [
    {
      path: '/home',
      component: home,
    },
    {
      path: '/about',
      component: about
    },
    {
      path: '/user/:id',
      component: user
    },
    {
      path: '/',
      redirect: '/home'
    }
  ]
})

记得将组件导入进来

import user from '../components/user.vue'

3.添加user.vue组件




computed定义dynamicSegment属性,用于获取动态id

三、嵌套路由

1.在home.vue中添加


2.在index.js定义路由

export default new Router({
  routes: [
    {
      path: '/home',
      component: home,
      children:[
        {
          path: 'phone',
          component: phone
        },
        {
          path: 'tablet',
          component: tablet
        },
        {
          path: 'computer',
          component: computer
        },
        //当进入到home时,显示默认组件
        {
          path: '',
          component: phone
        }
      ]
    },
    {
      path: '/about',
      component: about
    },
    {
      path: '/user/:id',
      component: user
    },
    {
      path: '/',
      redirect: '/home'
    }
  ]
})

3.添加phone.vue,tablet.vue,computer.vue组件
以phone.vue为例




贴上目录结构图


目录结构.jpg

【参考文章】

vue-router基本使用:https://www.cnblogs.com/SamWeb/p/6610733.html

你可能感兴趣的:(vue路由入门)