安装
npm i vue-router@3 (vue2.js就安装版本3)
在main.js 安装全局VueRouter
import Vue from "vue";
import App from "./App.vue";
// 安装全局的vuerouter
import VueRouter from "vue-router";
// 引入路由器
import router from "./router/index";
Vue.config.productionTip = false;
// 配置全局中间件
Vue.use(VueRouter);
new Vue({
render: (h) => h(App),
beforeCreate() {
Vue.prototype.$bus = this; //安装全局事件总线
},
// 使用路由
router,
}).$mount("#app");
App.vue里面写首页
- <router-link to="/goods">商品</router-link> 具体用于跳转到那 to=" "
- <router-view></router-view> 显示跳转过来的内容
<template>
<div>
<HeaderRouter></HeaderRouter>
<div class="left">
<ul>
<li><router-link to="/goods">商品</router-link></li>
<li><router-link to="/users">用户</router-link></li>
<li><router-link to="/setting">设置</router-link></li>
</ul>
</div>
<div class="right">
<router-view></router-view>
</div>
<div class="footer">底部</div>
</div>
</template>
<script>
import HeaderRouter from "@/components/HeaderRouter";
export default {
name: "App",
components: {
HeaderRouter,
},
};
</script>
<style scoped>
</style>
在src里面创建router 和里面 index.js(写路由)
- import VueRouter from "vue-router"; 引入vuerouter创建export default new VueRouter({(用于存放路由)})
- mode: "history", //修改连接格式
- path: "/users", 路由的名字 component: Users, //对应的组件名
- 二级路由用 children:[ ] (二级路由配置不需要写 “ / ” )
还可以通过路由来实现默认显示
children: [
// 默认显示
{
path: "",
redirect: "theme", //默认显示的路由名字
},
]
import VueRouter from "vue-router";
// 引入用户组件
import Users from "../views/Users";
// 引入商品组件
import Goods from "../views/Goods";
// 引入设置组件
import Setting from "../views/Setting";
// 主题设置
import themesetting from "@/views/themesetting";
// seo设置
import seosetting from "@/views/seosetting";
// 引入简介组件
import UsersInfo from "@/views/UsersInfo";
export default new VueRouter({
mode: "history", //修改连接格式
routes: [
// 一级路由
{
path: "/users",
component: Users, //对应的组件名
},
{
path: "/goods",
component: Goods,
},
{
path: "/UsersInfo",
component: UsersInfo,
},
{
path: "/setting",
component: Setting,
// 子路由
children: [
// 默认显示
{
path: "",
redirect: "theme",
},
// 组件中的二级路由
{
path: "theme", //
component: themesetting, //使用的组件名
},
{
path: "seo",
component: seosetting,
},
],
},
],
});
在src 中 的views存放组件
组件需要注意的有
- <router-link active-class="active" to="/setting/seo">seo设置</router-link> 二级路由to的时候需要写上一级路由的路由
<template>
<!-- 设置 -->
<div>
<ul>
<li>
<router-link active-class="active" to="/setting/theme">主题设置</router-link>
</li>
<li>
<router-link active-class="active" to="/setting/seo">seo设置</router-link>
</li>
<!-- <li><a href="#">SEO设置</a></li> -->
</ul>
<div class="box">
<router-view></router-view>
</div>
</div>
</template>
<style scoped>
</style>
动态路由字符串式,动态路由字符串式
<router-link :to="{ name: 'UsersInfo', params: { id: p.id } }">详情(动态路由对象式)</router-link>|
<router-link :to="`/UsersInfo/${p.id}`">详情(动态路字符串由式)</router-link>
动态路由需要在path加:id
name: "UsersInfo",
path: "/UsersInfo/:id",
component: UsersInfo,