1. 创建项目
- win + r,输入 cmd,打开终端
- 输入代码:cd desktop,定位到桌面
vue create xxx
(xxx 为项目名)
2. 目录内容
- node_modules:放置项目依赖的地方
- public:一般放置一些公用的静态资源,打包上线的时候,public 文件夹里面资源原封不动打包到 dist 文件夹里面。
- src:程序员源代码文件夹
(1)assets 文件夹:经常放置一些静态资源(图片)
(2)components 文件夹:一般放置非路由组件(或者项目共用的组件)
(3)App.vue 唯一的根组件
(4)main.js 入口文件(程序最先执行的文件)
(5)babel.config.js:babel 配置文件
(6)package.json:看到项目描述、项目依赖、项目运行指令
(7)README.md:项目说明文档
(8)pages 文件夹【自己创建】:放置路由组件
(9)router 文件夹【自己创建】:配置路由
3. 路由的配置
- 终端输入:npm i vue-router@3 【对应的是vue2.x版本】
- 在main.js 引入并注册路由
import router from '@/router'
new Vue({
render: (h) => h(App),
router,
}).$mount("#app");
- 注册路由信息:当这里书写router的时候,组件身上都拥有
$route
,$router
属性
(1)$route
:一般获取路由信息【路径、query、params】
(2)$router
:一般进行编程式导航进行路由跳转【push | replace】
- 在 src 目录下新建 router 文件,在该文件下创建 index.js 文件
// 配置路由的地方
import Vue from "vue";
import VueRouter from "vue-router";
// 使用路由插件
Vue.use(VueRouter);
// 引入路由组件
import Home from "@/pages/Home";
// 配置路由
export default new VueRouter({
// 配置路由
routes: [
{
path: "/home",
component: Home,
meta: {
show: true },
}
// 重定向,在项目跑起来的时候,访问/,立马让它指向首页
{
path: "*",
redirect: "/home",
},
],
});
4. 路由的跳转
- 声明式导航:
router-link
:必须要有 to 属性,指向跳转到的地址
<router-link to='/xxx'></router-link>
- 编程式导航:
$router.push | replace
,可以书写一些自己的业务
<button @click="xxx"></button>
methods:{
xxx() {
this.$router.push(......)
}
}
5. 路由的元信息
在 ./router/index.js 中使用
meta: {}
, 配置元信息
path: "/home",
component: Home,
meta: {
show: true}
.......
在 App 组件中用于隐藏和显示
<Footer v-show="$route.meta.show"/>
6. 路由传参
params 参数:属于路径当中的一部分,需要注意,在配置路由的时候,需要占位。
path: "/search/:keyword"
query 参数:不属于路径当中的部分,类似于 ajax 中的 queryString,不需要占位。
path: "/search"
- 字符串形式(路由传递参数)
this.$router.push('/search/' + this.keyword + '?k=' + this.keyword.toUpperCase())
- 模板字符串(路由传递参数)
this.$router.push(`/search/${
this.keyword}?k=${
this.keyword.toUpperCase()}`)
- 对象的形式:先给路由配置 name 属性,再传参
this.$router.push({
name: 'search', params: {
keyword: this.keyword}, query:{
k: this.keyword.toUpperCase()}})
接收
<div>
<h1>params参数————{
{
$route.params.keyword }}</h1>
<h1>query参数————{
{
$route.query.k }}</h1>
</div>
7. 路由传参的面试题
- 路由传递参数(对象写法),path 是否可以结合 params 参数一起使用?
答:路由跳转传参的时候,对象的写法可以是 name、 path 形式,但是需要注意的是,path 这种写法不能与 params 参数一起使用。
- 如何指定 params 参数可传和不可传?
答:如果要求传递 params 参数,但是并没有传递,则地址栏的 URL 会有问题。我们可以在配置路由的时候,在占位符的后面加上一个问号 (path: "/search/:keyword?"
)【params 可以传递或者不传递】,此时地址栏的 URL 不会发生错误。
- params 参数可以传递也可以不传递,但是如果传递的是空字符串,如何解决?
答:使用 undefined
解决:params 参数可以传参、不传参(空字符串)
this.$router({
name: 'search', params: {
keyword: ''||undefined}, query: {
k: this.keyword.toUpperCase()}})
- 路由能不能传递 props 数据?
答案:可以。
扫描二维码关注公众号,回复:
14222293 查看本文章
![](/qrcode.jpg)
- 布尔值写法:只能传递 params 参数:
props:true
- 对象写法:额外的给路由传递一些参数:
props: {a: 1, b: 2}
- 函数写法:可以传递 params 参数,也可以传递 query 参数,通过 props 传递给路由组件。
props: ($route) => ({
keyword: $route.params.keyword, k: $route.query.k})