安装
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里面写首页
- <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>
-
- <script>
- import HeaderRouter from "@/components/HeaderRouter";
- export default {
- name: "App",
- components: {
- HeaderRouter,
- },
- };
- script>
-
- <style scoped>
-
- style>
在src里面创建router 和里面 index.js(写路由)
还可以通过路由来实现默认显示
- 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存放组件
组件需要注意的有
-
- <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>
-
- ul>
- <div class="box">
- <router-view>router-view>
- div>
- div>
- <style scoped>
-
- style>
动态路由字符串式,动态路由字符串式
-
"{ name: 'UsersInfo', params: { id: p.id } }">详情(动态路由对象式) | - <router-link :to="`/UsersInfo/${p.id}`">详情(动态路字符串由式)router-link>
动态路由需要在path加:id
- name: "UsersInfo",
- path: "/UsersInfo/:id",
- component: UsersInfo,