• Welcome to Journal web site.

我是 PHP 程序员

- 开发无止境 -

Next
Prev

Vue3 路由

Data: 2019-12-01 15:04:24Form: JournalClick: 9

# Vue3 路由

# 一、安装路由

  • 官网:https://v3.cn.vuejs.org/guide/routing.htmlopen in new window
  • 官网手册:https://next.router.vuejs.org/zh/open in new window

# 1、创建新项目

# 1、创建一个项目
vue create vuecli

# 2、选择:用vue2,vue3,手动配置。 vue2,vue3除了基本语法, 还有下面2个功能
# 2.1、babel 把es6的语法,转成es5的语法,可以做到兼容
# 2.2、eslint 语法检查,约束你的代码习惯
please pick a preset:
  Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint)
  Manually select features

# 3、手动选择功能:Choose Vue version、Babel、CSS Pre-processors、Router、Vuex
Check the features needed for your project:
  Choose Vue version                  // 版本
  Babel                               // 把es6的语法,转成es5的语法,可以做到兼容
  TypeScript                          // 由微软开发的自由和开源的编程语言,是 JavaScript 的一个超集,支持es6语法
  Progressive Web App (PWA) Support   // Web APP开发
  Router                              // 路由
  Vuex                                // 状态管理器
  CSS Pre-processors                  // css预处理器:三种流行的CSS预处理器:Sass、LESS 和 Stylus
  Linter / Formatter                  // 语法检查器(eslint)
  Unit Testing                        // 单元测试
  E2E Testing                         // e2e(端到端)测试

# 4、选择版本:3.x
Choose a version of Vue.js that you want to start the project with:
  2.x
  3.x

# 5、选择路由:Yes 路由有2种模式:hash路由、history路由(历史路由)
Use history mode for router? (Requires proper server setup for index fallback in production)
    y
    n

# 5、选择css预处理器版本:dart-sass,官方目前主力推dart-sass
Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
  Sass/SCSS (with dart-sass)
  Sass/Scss (with node-sass)
  Less
  Stylus

# 6、配置文件:In package.json
Where do you prefer placing config for Babel, ESlint, etc.?
  In dedicated config files   // 独立配置文件
  In package.json             // 放在package.json里

# 7、是否保持此项目配置:保存的话,起个名字
Save this as a preset for future projects?
  y   // 保存
  n   // 不保存


# 8、安装完成后,会在package.json文件中的dependencies参数中,增加vue-router(路由)、vuex(状态管理)
# 9、增加路由配置目录:`src/router`
# 10、新增页面目录:`src/views`

# 2、关闭语法检查器(eslint)

# 新建/vue.config.js文件
module.exports = {
    // 关闭eslint检查
    lintOnSave: false,
    devServer: {
        overlay: {
            warnings: false, //不显示警告
            errors: false, //不显示错误
        }
    }
};

# 二、路由介绍(Vue Route)

  • 跳转到当前页面前,进行操作
  • 离开当前页面后,进行操作
  • 路径名称,别名
  • 获取url:完整url,不带域名url
  • url上的参数

# 三、路由操作

# 1、配置新路由

# 1、主入口文件:main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'   // 这个完整路径是 './router/index.js',省略了index.js,也可以改变这个文件,比如a.js,就需要配置了
import store from './store'     // 这个完整路径是 './store/index.js'

createApp(App).use(store).use(router).mount('#app')


# 2、路由文件:router/index.js
# 2.1、引入vue路由,使用 createRouter, createWebHistory 方法
// 还可以引入createWebHashHistory,hash模式路由
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

# 2.4、定义多个页面的指向,可以直接把这里的数据,放到 router 变量里。写100个就要加100个
# 2.4.1、path 是url路径,域名后面的路径,不要重复
# 2.4.2、name 页面起个名字,通过名字可以找到组件,不要重名
# 2.4.3、component 页面路径,2种引入方式,先创建2个页面
const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: () => import('../views/About.vue')
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes  # 2.3、这个就是上面的变量,数据应该是 routes:routes,es6写法省略了一个。
})
# 2.2、export default 输出 router 变量,谁引用这个文件,就使用这个变量
export default router


# 3、新增 src/views/User.vue 文件
<template>
    <div>
        <h1>这是用户中心页面</h1>
    </div>
</template>
<script>
export default {
    name: "User",
};
</script>


# 4、新增 src/views/Course.vue 文件
<template>
    <div>
        <h1>这是课程列表页面</h1>
    </div>
</template>
<script>
export default {
    name: "Course",
};
</script>


# 5、配置页面路由
# 5.1、component: () => import('../views/About.vue') ,懒加载模式,每个vue文件,单独打包一个js。
  建议用这个:https://v3.cn.vuejs.org/guide/ssr/routing.html#%E4%BB%A3%E7%A0%81%E5%88%86%E7%A6%BB
# 5.2、component: User,引入vue文件,在使用。这个会把所有vue文件的js打包在一个文件
import User from '../views/Course.vue'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: () => import('../views/About.vue')
    },
    {
        path: '/user',
        name: 'User',
        component: User
    },
    {
        path: '/course',
        name: 'Course',
        component: () => import('../views/Course.vue')
    }
]

# 5.3、可以打包看一下js文件的数量:yarn build
# 5.4、访问新页面 localhost:8080/user、localhost:8080/course


# 6、hash模式:createWebHashHistory
import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
const router = createRouter({
    // history: createWebHistory(process.env.BASE_URL),
    history: createWebHashHistory(process.env.BASE_URL),    // 用hash方法
    routes
})
# 6.1、访问路径就会多个#号 localhost:8080/#/user、localhost:8080/#/course

# 2、使用路由

# 1、App.vue文件:使用路由
<template>
    <div id="nav">
        <router-link to="/">首页</router-link> |
        <router-link to="/about">帮助中心</router-link> |
        <router-link to="/course">课程列表</router-link> |
        <router-link to="/user">个人中心</router-link>
    </div>
    <router-view />
</template>


# 2、样式
<style>
    #nav a.router-link-exact-active {
        color: red;
    }
</style>

# 3、a标签也能跳转路由,但不建议使用
# 3.1、router-link标签,vue渲染以后,就是a标签。
# 3.2、router-link标签 使得 Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码
<template>
    <div id="nav">
        <router-link to="/">首页</router-link> |
        <router-link to="/about">帮助中心</router-link> |
        <router-link to="/course">课程列表</router-link> |
        <a href="/user">个人中心</a>
    </div>
    # 4、router-view 将显示与 url 对应的组件。你可以把它放在任何地方,以适应你的布局
    <router-view />
</template>

# 3、路由全局变量

  • $route 获取当前路由
  • $router 获取当前路由器,分发器:可以进行页面跳转
<template>
    <div id="nav">
        <router-link to="/">首页</router-link> |
        <router-link to="/about">帮助中心</router-link> |
        <router-link to="/course">课程列表</router-link> |
        # 1、标签 `$route` 获取当前路由
        <a href="/user" :class="{active:$route.path=='/user'}">个人中心</a>
        # 2、标签跳转 `$router` 获取当前路由器,分发器:可以进行页面跳转
        <button @click="$router.push('/course')">跳转</button>
    </div>
    <router-view />
</template>
<style>
.active {
    color: red !important;
}
</style>


# 3、方法跳转
<template>
    <div id="nav">
        <router-link to="/">首页</router-link> |
        <router-link to="/about">帮助中心</router-link> |
        <router-link to="/course">课程列表</router-link> |
        <a href="/user" :class="{active:$route.path=='/user'}">个人中心</a>
        <button @click="go_url('/course')">跳转</button>
    </div>
    <router-view />
</template>
<script>
export default {
    methods: {
        go_url(url) {
            // 这样会报错的,要加上 this 当前
            // $router.push(url);

            this.$router.push(url);
            // 查看当前路由的信息
            console.log(this.$route);
        }
    }
};
</script>

// router-link 标签,可以更改
// router-view 标签,不能更改。将显示与 url 对应的组件。你可以把它放在任何地方,以适应你的布局

# 4、嵌套路由(子路由)

# 1、新增 src/views/Userinfo.vue 文件
<template>
    <div>
        <h1>这是用户 个人信息页面</h1>
    </div>
</template>

# 2、新增 src/views/Userconfig.vue 文件
<template>
    <div>
        <h1>这是用户 个人配置页面</h1>
    </div>
</template>

# 3、User.vue 文件,创建个人中心样式
<template>
    <div>
        <h1>这是个人中心页面</h1>
        <div class="menu">
            <ul>
                <li>
                    <router-link to="/user/config">个人设置</router-link>
                </li>
                <li>
                    <router-link to="/user/info">个人信息</router-link>
                </li>
            </ul>
        </div>
        <div class="main">
            <router-view />
        </div>
    </div>
</template>
<style scoped>
.menu {
    width: 30%;
    height: 300px;
    float: left;
    background: #42b983;
}
.main {
    width: 65%;
    height: 300px;
    float: right;
    background: #aaaaaa;
}
a {
    font-weight: bold;
    color: #2c3e50;
}
.router-link-exact-active {
    color: red;
}
</style>

# 4、router/index.js
# 4.1、配置嵌套路由(子路由),在父路由里,增加 children 参数
const routes = [
    {
        path: "/",
        name: "Home",
        component: Home
    },
    {
        path: "/about",
        name: "About",
        component: () => import("../views/About.vue")
    },
    {
        path: "/user",
        name: "User",
        component: () => import("../views/User.vue"),
        children: [
            {
                // 子路由的path,没有/
                path: "config",
                name: "Userconfig",
                component: () => import("../views/Userconfig.vue")
            },
            {
                path: "info",
                name: "Userinfo",
                component: () => import("../views/Userinfo.vue")
            }
        ]
    },
    {
        path: "/course",
        name: "Course",
        component: () => import("../views/Course.vue")
    }
];

# 5、动态路由

# 1、router/index.js
# 1.1、路径参数 用冒号 : 表示
{
    path: "/course/:id",
    name: "Course",
    component: () => import("../views/Course.vue"),
}

# 2、访问url
localhost:8080/course/10
localhost:8080/course   // 这样就不能访问了

# 3、获取参数
# 3.1、当一个路由被匹配时,它的 params 的值将在每个组件中以 this.$route.params 的形式暴露出来
<template>
    <div>
        <h1>这是课程列表页面</h1>
        # 3.2、路由配置的是id,接收key就是id。 配置的是uid,接收的key就是uid
        {{ $route.params.id }}
        # 3.3、js 获取参数
        {{ one() }}
    </div>
</template>
<script>
export default {
    methods: {
        one() {
            // 3.3.1、js 获取参数
            console
                
                
                
                
                
                
              
Name:
<提交>