vue router使用完整教程详解

Vue Router是用于Vue.js应用程序中实现路由的官方库,它允许你创建单页面应用(SPA)并管理页面之间的导航。下面是Vue Router的完整使用教程:

安装Vue Router:使用npm或yarn安装Vue Router。

shell

npm install vue-router

创建Vue Router实例:在你的Vue应用中,创建一个Vue Router实例,并配置路由规则。

js

// main.js

import Vue from 'vue';

import VueRouter from 'vue-router';

import Home from './components/Home.vue';

import About from './components/About.vue';

 

Vue.use(VueRouter);

 

const routes = [

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

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

];

 

const router = new VueRouter({

  routes,

});

 

new Vue({

  router,

  render: h => h(App),

}).$mount('#app');

创建路由组件:在Vue应用中创建对应的路由组件。

vue

<!-- Home.vue -->

<template>

  <div>

    <h1>Home</h1>

    <router-link to="/about">Go to About</router-link>

  </div>

</template>

 

<script>

export default {

  // ...

};

</script>

 

vue

<!-- About.vue -->

<template>

  <div>

    <h1>About</h1>

    <router-link to="/">Go to Home</router-link>

  </div>

</template>

 

<script>

export default {

  // ...

};

</script>

渲染路由视图:在Vue组件中,使用<router-view>标签来渲染对应的路由组件。

vue

<!-- App.vue -->

<template>

  <div>

    <h1>My App</h1>

    <router-view></router-view>

  </div>

</template>

 

<script>

export default {

  // ...

};

</script>

嵌套路由:可以在一个组件中嵌套多个路由,并在内部定义子路由规则。

js

const routes = [

  {

    path: '/',

    component: Home,

  },

  {

    path: '/about',

    component: About,

    children: [

      {

        path: 'contact',

        component: Contact,

      },

    ],

  },

];

获取路由参数:使用$route.params或$route.query来获取路由参数。

vue

<!-- Contact.vue -->

<template>

  <div>

    <h1>Contact</h1>

    <p>Contact ID: {{ $route.params.id }}</p >

  </div>

</template>

 

<script>

export default {

  // ...

};

</script>

以上是Vue Router的基本用法。Vue Router还提供了其他一些高级功能,如路由守卫、动态路由、路由过渡等。你可以查阅Vue Router的官方文档以获取更详细的使用教程和示例代码:https://router.vuejs.org/zh/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值