vue-router的基本使用

@路由的基本使用:
1.通过Vue.use(插件)安装插件
2.配置路由和组件之间的映射关系
3.导出对象传入到vue实例中
4.挂载

创建Home,About,User三个组件
Home.vue

<template>
  <div>
    <h2>我是首页</h2>
    <p>哈哈哈</p>
  </div>
</template>

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

<style scoped>

</style>

About.vue

<template>
  <div>
    <h2>我是关于</h2>
    <p>呵呵呵</p>
  </div>
</template>

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

<style scoped>

</style>

User.vue

<template>
  <div>
    <h2>我是我的</h2>
    <p>嘻嘻嘻</p>
    {{UserId}}
  </div>
</template>

<script>
export default {
  name: "User",
  computed:{
    UserId(){
      return this.$route.params.userid
    }
  }
}
</script>

<style scoped>

</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'
//方法一
// import Home from "../components/Home";
// import About from "../components/About";
// import User from "../components/User";

//方法二:router懒加载
const Home = () => import("../components/Home")
const About = () => import("../components/About")
const User = () => import("../components/User")

//1通过Vue.use(插件)安装插件
Vue.use(Router)
//2配置路由和组件之间的映射关系,注意关键字routes,不要写成router或routers
const routes = [
  //redirect重定向,首次加载浏览器时就显示Home
  {
    path: '',
    redirect:'/home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/user/:userid',
    component: User
  }
]
//3导出对象传入到vue实例中
export default new Router({
  routes,
  mode:'history',  //hash模式转为html5的history模式(去#号)
  linkActiveClass:'active'
})

App.vue

<template>
  <div id="app">
<!--     replace:不会留下history记录,返回键不能按-->
    <router-link to="/home" tag="button" replace>首页</router-link>
    <router-link to="/about" tag="button" replace>关于</router-link>
<!--    动态绑定路由-->
    <router-link :to="'/user/'+userId" tag="button" replace>我的</router-link>
<!--    router-view决定渲染位置-->
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  //组件里的数据data必须是函数
  data(){
    return{
      userId:'zhangsan'
    }
  }
}
</script>

<style>
</style>

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  data:{
    message:'123'
  },
  router, //挂载
  //箭头函数
  // (h) => {
  //     return h(App)
  // }
  render: h => h(App) //省略写法
})

路由懒加载后会出现以下文件:
在这里插入图片描述
运行结果:
在这里插入图片描述

点击我的:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值