欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > VueRouter的使用

VueRouter的使用

2024/10/24 9:23:52 来源:https://blog.csdn.net/qq_64536562/article/details/141096457  浏览:    关键词:VueRouter的使用

  路由的封装抽离:在src目录下新建router文件夹,router文件下新建index.js文件,在里面配置路由。好处:拆分模块,利于维护。

一、5个基本步骤

1.下载:下载VueRouter模块到当前工程。命令:npm i vue-router@3

2.引入:

import Vue from 'vue'

import VueRouter from 'vue-router'

3.安装注册:Vue.use(VueRouter)

4.创建路由对象:const router = new VueRouter( )

5.注入:将路由对象注入到new Vue实例中,建立关联。

new Vue({

  render: h => h(App),

  router

}).$mount('#app')

二、2个核心步骤

1.创建需要的组件(views目录),配置路由规则(路径和组件的匹配关系)。

2.配置导航,配置路由出口 router-view (路径对应的组件显示的位置)

router 下的index.js如下

//  @/views 绝对路径 : 基于 @ 指代 src 目录,从 src 目录出发找组件
import Find from '@/views/Find'
import My from '@/views/My'
import Friend from '@/views/Friend'import Vue from 'vue'
import VueRouter from 'vue-router'//VueRouter插件初始化
Vue.use(VueRouter)//创建路由对象
const router = new VueRouter({//路由规则们,数组包对象。一条路由规则{path:路径,component:组件}routes: [{ path: '/find', component: Find },{ path: '/my', component: My },{ path: '/friend', component: Friend }],//自定义类名linkActiveClass: 'active',   //配置模糊匹配的类名linkExactActiveClass: 'exact-active'   //配置精确匹配的类名
})export default router

App.vue如下(简单介绍 router-link )

<template><div><div class="footer_wrap"><!-- 1.router-link是什么?vue-router提供的全局组件,用于替换a标签2.router-link怎么用?<router-link to="/路径值"></router-link>必须传入to属性,指定路由路径值3.router-link好处?能跳转,能高亮(自带激活时的类名)            --><router-link to="/find">发现音乐</router-link><router-link to="/my">我的音乐</router-link><router-link to="/friend">朋友</router-link></div><div class="top"><!-- 路由出口(所匹配的组件展示的位置) --><router-view></router-view></div></div>
</template><script>
export default {};
</script><style>
/* router-link 会自动给当前导航添加两个类名 区别 */
/*  1. router-link-active 模糊匹配(用的多) to='/find => 地址栏/find  /find/one  /find/two *//*  2. router-link-exact-active  精确匹配 to='/find => 地址栏/find */
.footer_wrap a.active {background-color: red;
}body {margin: 0;padding: 0;
}
.footer_wrap {position: relative;left: 0;top: 0;display: flex;width: 100%;text-align: center;background-color: #333;color: #ccc;
}
.footer_wrap a {flex: 1;text-decoration: none;padding: 20px 0;line-height: 20px;background-color: #333;color: #ccc;border: 1px solid black;
}
.footer_wrap a:hover {background-color: #555;
}</style>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com