刘刚刚的个人博客

3.Vue基础——Vue-router的使用

创建时间:2020-06-22 17:41:22
更新时间:2020-06-22 17:41:22

使用Vue-router 更方便的管理单页面应用的路由提高页面加载速度。

vue-router的使用

如果在初始化的时候选择了安装vue-router 则不需要以下安装步骤

安装

npm install vue-router -S

配置

  1. 初始化路由对象

    在根目录创建router文件夹,并创建index.js

    import Vue from "vue";
    import Router from "vue-router";   //1.引入路由
    
    import Reg from '../components/reg'
    import Goods from '../components/goods'
    
    Vue.use(Router)   //2.注册路由
    
    //3.暴露路由,供main.js 使用
    export default new Router({
      mode:'history',
      routes:[
        {
          name:'Reg',
          path:'/reg',
          component:Reg
        },
        {
          name:'goods',
          path:'/goods',
          component:Goods
        }
      ]
    })
    
  2. 注册路由信息

    import Vue from 'vue'
    import App from './App'
    import router from './router/index'
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,    //此处必须使用小写
      components: { App },
      template: '<App/>'
    })
  3. 在App.vue中使用router组件

    <template>
      <div id="app">
        <div>App</div>
        <router-view/>  //此处一定为 router-view 标签
      </div>
    </template>
    
    <script>
    export default {
      name: 'App',
    }
    </script>
    
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>

    使用

    在安装配置好vue-router后,可以使用以下两个对象

    1. this.$router 可以在js代码中进行页面的跳转
    2. this.$route 可以用与获取地址栏上的url参数

#### 页面的跳转

  1. router-link标签

    <router-link to="/user"></router-link>     //根据path 跳转
    <router-link :to="{name:'user'}"></router-link> //根据路由的name跳转
  2. js中

    可以在站内进行跳转,如果进行站外跳转需要使用 loaction.href="url"

    jump(){
        this.$router.push('/user')
        this.$router.back()  //返回上一页
        this.$router.go(-1) //返回n页
        this.$router.forward() //跳转到下一页 
    }

#### 参数传递

  1. 查询字符串(路径中问号后边的参数)

    //`http://localhost:8008/user?name=shuta
    let  name = this.$router.query.name
  2. 路由参数

    在路由路径中使用路由参数时

    //router/index.js
    {
          name:"User",
          path: "/user/:id",
          component: User
    }
    
    //.vue
    <router-link to="/user/100"></router-link>
    
    //user.vue
    let id = this.$router.params.id
我的名片

昵称:shuta

职业:后台开发(python、php)

邮箱:648949076@qq.com

站点信息

建站时间: 2020/2/19
网站程序: ANTD PRO VUE + TP6.0
晋ICP备18007778号