三十二、Vue-router入门

版权声明:本文为博主原创文章,未经博主允许欢迎转载,请注明原文链接。一起交流,共同进步。 https://blog.csdn.net/newbie_907486852/article/details/83478228

                                    Vue-router入门


      由于Vue在开发时对路由支持的不足,后来官方补充了vue-router插件,它在Vue的生态环境中非常重要,在实际开发中只要编写一个页面就会操作vue-router。要学习vue-router就要先知道这里的路由是什么?这里的路由并不是指我们平时所说的硬件路由器,这里的路由就是SPA(单页应用)的路径管理器。再通俗的说,vue-router就是我们WebApp的链接路径管理系统

      有的小伙伴会有疑虑,为什么我们不能像原来一样直接用<a></a>标签编写链接哪?因为我们用Vue作的都是单页应用,就相当于只有一个主的index.html页面,所以你写的<a></a>标签是不起作用的,你必须使用vue-router来进行管理。

1、安装vue-router

      vue-router是一个插件包,所以我们还是需要用npm来进行安装的。打开命令行工具,进入你的项目目录,输入下面命令

    npm install vue-router --save-dev

2、router/index.js文件

      我们用vue-cli生产了我们的项目结构,你可以在src/router/index.js文件,这个文件就是路由的核心文件,我们先解读一下它。
      这个文件定义了我们的所有路由。

import Vue from 'vue'   //引入Vue
import Router from 'vue-router'  //引入vue-router
import Hello from '@/components/Hello'  //引入根目录下的Hello.vue组件
import Hi from '@/components/Hi'

Vue.use(Router)  //Vue全局使用Router

export default new Router({
  routes: [              //配置路由,这里是个数组
    {                    //每一个链接都是一个对象
      path: '/',         //链接路径:使用这个链接可以跳转到component声明的页面
      name: 'Hello',     //路由名称
      component: Hello   //对应的组件模板:跳转的页面
    },{
      path:'/hi',
      name:'Hi',
      component:Hi
    }
  ]
})

3、路由跳转的页面

Hi.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
  export default {
    name: 'hi',
    data () {
      return {
        msg: 'Hi, I am 杨胖子'
      }
    }
  }
</script>
<style scoped>
</style>

4、App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">

    <p>导航 :
      <router-link to="/">首页</router-link>     
      <!--声明跳转的链接(在router/index.js文件定义)-->
      <router-link to="/Hi">Hi页面</router-link>
    </p>
    <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>

猜你喜欢

转载自blog.csdn.net/newbie_907486852/article/details/83478228
今日推荐