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

一、创建项目

环境版本信息,尽量接近

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

在原有基础上额外选择Router

回车后选择默认2.x

之后全都选择默认值。

二、跳转前页面

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

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

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

<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内容

<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>

其中

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

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

三、跳转后页面

修改原有about页面

<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。

 

posted @ 2020-11-18 10:44  喵星兔  阅读(167)  评论(0编辑  收藏  举报