喵星之旅-狂奔的兔子-vue页面跳转及传值

一、创建项目

环境版本信息,尽量接近

Alt text

使用vue create 命令创建项目,并选择自定义(如图)
Alt text

在原有基础上额外选择Router

Alt text

回车后选择默认2.x

Alt text

之后全都选择默认值。

二、跳转前页面

新加页面用于跳转/views/Login.vue

修改/router/index.js,添加Login相关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path: '/login',
name: 'Login',
component: () => import( '../views/Login.vue')
}
]

const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})

export default router

修改该app.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/login">login</router-link>
</div>
<router-view/>
</div>
</template>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}

#nav {
padding: 30px;
}

#nav a {
font-weight: bold;
color: #2c3e50;
}

#nav a.router-link-exact-active {
color: #42b983;
}
</style>

其中Login.vue内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<div>
<input v-model="message" >
<button v-on:click="about">about</button>
</div>
</template>

<script>

export default {
data() {
return {
message:''
}
},
methods: {
about() {
this.$router.push({
name: "About",
params:{name: '123' + this.message}
});
}
}

}
</script>

<style>

</style>

其中

1
2
3
4
this.$router.push({
name: "About",
params:{name: '123' + this.message}
});

name的值为跳转页面,params的内容为传参内容,params中的name和任何页面元素无关,仅用来传参。

三、跳转后页面

修改原有about页面

1
2
3
4
5
6
<template>
<div class="about">
<h1>This is an about page</h1>
<h1>{{ this.$route.params.name }}</h1>
</div>
</template>

其中this.$route.params.name为接收参数,这里面的name就是传参的name。

文章目录
  1. 一、创建项目
  2. 二、跳转前页面
  3. 三、跳转后页面
|