美文网首页
Vue-router

Vue-router

作者: 苹果咏 | 来源:发表于2021-03-24 21:10 被阅读0次
跳转方式

第一种:普通跳转

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    linkToHome () {
      this.$router.push('./')
    },
    linkToAbout () {
      this.$router.push('./about')
    }
  }
}
</script>

第二种:代码跳转

<template>
  <div id="app">
    <div id="nav">
      <button @click="linkToHome">首页</button>
      <button @click="linkToAbout">关于</button>
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    linkToHome () {
      this.$router.push('./')
    },
    linkToAbout () {
      this.$router.push('./about')
    }
  }
}
</script>

都要定义路由文件:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})

export default router

动态路由

 {
    path: '/user/:id',
    name: 'User',
    component: () => import('../views/User.vue')
  }
// User组件
<template>
  <div>
    <p>User {{ $route.params.id }}</p>
  </div>
</template>

<script>
export default {

}
</script>

// App.vue
<template>
  <div id="app">
    <div id="nav">
      <router-link :to="'/user/'+id">User</router-link>
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      id: 'lili'
    }
  }
}
</script>

路由懒加载

vue-cli4脚手架的代码已经有懒加载路由

  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },

子路由

  {
    path: '/user/:id',
    name: 'User',
    component: () => import('../views/User.vue'),
    children: [
      {
        path: '/user/:id/content',
        component: () => import('../views/User_content.vue')
      }
    ]
  }

相关文章

网友评论

      本文标题:Vue-router

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