路由vue-router的基本使用

一、编写router配置项(在router文件夹的index.js文件中编写)

import Vue from 'vue'//引入vue
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
// import HomeView from '@/views/HomeView.vue'

// 使用router插件
Vue.use(VueRouter)

//创建router对象,匹配路由规则
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = new VueRouter({//实例化对象
  routes,
  // mode:'hash'
  mode:'history'

})

export default router
// 总结:1安装路由 2写路由规则 3挂载main.js   4根组件中写router-link组件和路由出口

二、在main.js中进行引入和挂载

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

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

三、在根组件中使用

<template>
  <div id="app">
    <nav>
      <!-- <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> -->
      <!-- tag="h2"更改a标签 -->
      <h2 @click="gohome">Home</h2>
      <h2 @click="goabout">About</h2>

    </nav>
    <!-- 路由出口 :指定展示位置 -->
    <router-view/>

  </div>
</template>
<script>
  export default {
      name:'APP',
      methods: {
			/* 第一种
			gohome() {
              this.$router.push('/')
			},
			goabout() {
               this.$router.push('/about')
			} */
			
			/* 第二种 */
			// gohome() {
			//   this.$router.push({path:'/'})
			// },
			// goabout() {
			//    this.$router.push({path:'/about'})
			// }
			
      /* 第3种 */
			// gohome() {
			//   this.$router.push({name:'home'})
			// },
			// goabout() {
			//    this.$router.push({name:'about'})
			// } 
		}
  }
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值