11.0、vue-router路由

11.0、vue-router路由

第一步:安装vuerouter,要在当前项目下的控制台执行这段命令行

用npm install vue-router --save-dev

 

第二步:导入vue-router

import VueRouter from 'vue-router'
//显示声明使用VueRouter
Vue.use(VueRouter);

 

由于这里npm-router安装后一直报错无法运行,好像是版本的问题。所以我直接重新创建了一个新项目,并且在创建项目的时候,勾选自动下载npm-router

第三步:在components文件夹下创建一个自己的组件Main.vue

<template>
    <h1>首页</h1>
</template>
<script>
export default {
  name: 'Main'
}
</script>
<style scoped>
</style>

再创建一个Content.vue组件

<template>
  <h1>内容页</h1>
</template>

<script>
export default {
  name: 'Content'
}
</script>
<style scoped>
</style>

第四步:在router文件夹下创建一个路由配置文件index.js

import Vue from 'vue'
import Router from 'vue-router'
import Content from '../components/Content'
import Main from '../components/Main'

//安装路由
Vue.use(Router)
export default new Router({
  routes: [
    {
      // 路由路径
      path: '/content',
      name: 'content',
      // 跳转的组件
      component: Content
    },
    {
      // 路由路径
      path: '/Main',
      name: 'Main',
      // 跳转的组件
      component: Main
    }
  ]
})

第五步:在main.js文件中配置一下路由

import Vue from 'vue'
import App from './App'
//这里会自动扫描router文件夹下的js路由配置文件并导入过来
import router from './router'

Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  // 配置路由
  router,
  components: { App },
  template: '<App/>'
})

第六步:在app.vue中加入Main组件和Content组件测试路由是否可用即可

<template>
  <div id="app">
    <router-link to="/Main">首页</router-link>
    <router-link to="/Content">内容页</router-link>
    <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>

总结一下:

这些文件之间的关系,首先解释一下main.js里的代码如下:

 

        整个router路由流程其实就是:先创建了两个组件分别是主页和内容页,然后在router路由

index.js文件里注册一下路径和要跳转的组件,最后在App组件中加上需要的组件即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值