2

Vue router路由设计

 3 months ago
source link: https://blog.51cto.com/u_15640304/9975369
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Vue router路由设计_路由配置

这里的路由是指的页面之间的路径管理器,简单的理解为 vue-router 就是链接路径的管理系统。vue-router 是 Vue.js 官方的路由插件,它和 vue.js 是深度集成的,适合用于构建单页面应用。vue-router 就是将组件映射到路由上面。在 vue-router 单页面应用中,是路径之间的切换,也就是组件的切换。

vue router 路由配置

在 Vue 中,路由的配置都是在 router 中的 index.js 中进行的配置。

首先在 components 创建两个 Vue 组件,分别是 SignIn.vue 和 SignUp.vue。这两个文件的内容分别是

SignIn.vue

<template>

    <div class='login-form'> 

        <h1>登录</h1>

        <v-text-field label="用户名"></v-text-field>

        <v-text-field type="password" label="密码"></v-text-field>

        <v-btn color='primary'>登录</v-btn>

        <v-btn color='primary' text>注册</v-btn>

    </div>

</template>

SignUp.vue

<template>

    <div class='sign-up'>

        <h1>注册</h1>

        <v-text-field lable="用户名"></v-text-field>

        <v-text-field lable="密码" type='password'></v-text-field>

        <v-text-field lable="邮箱"></v-text-field>

        <v-btn color='primary'>注册</v-btn>

        <v-btn color='primary' text>去登陆</v-btn>

    </div>

</template>

这两个页面分别是登录界面和注册界面,这就需要用到 router 中的 index.js 文件来管理路由了。

首先我们在已有的项目中找到 index.js 的文件,默认内容如下:

// 配置路由规则

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: function () {

      return import(/* webpackChunkName: "about" */ '../views/About.vue')

    }

  }

]

现在将上述的 SignIn.vue 和 SignUp.vue 两个组件进行配置。

首先是要在 index.js 里面配置两个组件的路由

1、在 index.js 导入这两个组件

import SignIn from '../components/SignIn.vue'

import SignUp from '../components/SignUp.vue'

2、在 index.js 配置路由信息

{

    path:'/',          # 这里的 path:'/' 是页面可以访问的路径

    name:'SignIn',     # 作为这个路由的标识

    component:SignIn   # 指定组件

  },

  {

    path:'/sign-up',

    name:'SignUp',

    component:SignUp

  }

3、接下来就是如何触发页面之间的跳转,首先是需要在页面下的 <script> 标签下的 methods 创建一个方法,这里命名为 signUp()

代码如下:

<script>

export default {

    methods: {

            signUp(){

            this.$router.push({name:'SignUp'})  # 这里的 name:'SignUp' 是在 index.js 路由配置 name

        }

    }

}

4、给控件绑定一个事件,这里使用 @click='signUp()' 监控点击事件。当点击这个 button 的时候,就会触发 signUp 方法。

<v-btn color='primary' text @click="signUp()">注册</v-btn>

vue router 路由设计就先说到这里啦,大家可以多多练习一下哦~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK