Vue中使用vue-router 路由

本文介绍了如何在Vue项目中使用vue-router进行路由配置。首先通过npm安装vue-router,然后定义组件如Content.vue和Main.vue。接着在index.js中配置路由,最后在APP.vue和main.js中完成路由的导入和展示。测试环节验证了路由功能的正确性。

vue-router 路由

  • 当前项目下 npm install vue-router --save-dev
    • npm install vue-router 安装路由
    • –save-dev 保存在dev的配置中

使用方法

项目目录结构

在这里插入图片描述

1.定义组件

自定义组件Content.vue和Main.vue

Content.vue

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

<script>
    export default {   //导出 让外部能够使用import导入
        name: "Content" 
    }
</script>

<style scoped>

</style>

Main.vue

<template>
    <h1>首页</h1>
</template>

<script>
    export default {
        name: "Main"
    }
</script>

<style scoped>

</style>

2.配置路由

index.js

import Vue from 'vue';
import VueRouter from "vue-router";   //导入路由
import Content from '../components/Content';  //导入组件
import Main from '../components/Main';
//安装路由
Vue.use(VueRouter);

//配置路由
export default new VueRouter({
  routes: [
    {
      //路由的路径  请求的路径
      path: '/content',
      name: 'Content',
      //跳转的组件
      component: Content
    },
    {
      path: '/main',
      name: 'Main',
      component: Main,
    }
  ]
});

3.在APP.vue中展示

<template>
  <div id="app">
    <router-link to="/main">首页</router-link>  <!--控制跳转   相当于html中的a链接-->
    <router-link to="/content">内容页</router-link>
    <router-view></router-view>  <!--控制页面的展示,将请求对应模板的内容展示在标签的位置-->
  </div>
</template>

<script>

export default {
  name: 'App',
  components: {
  }
}
</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>

4main.js中导入路由配置

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/>'
})
测试

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值