Vue-cli3如何添加路由(vue-router)

之前使用的vue-cli2的是否可以在创建项目时直接引入vue-router,但是现在Vue-cli3新建项目后却少了很多东西,我们需要自己来安装使用路由。具体方案如下:

安装路由

npm install vue-router
创建router.js与main.js同级
在这里插入图片描述
router.js中的内容为

import Vue from 'vue'
import Router from 'vue-router'
 
//组件模块
import Main from './components/content/main'
import Header from './components/header/header'
import Admin from './components/admin/admin'
 
Vue.use(Router)
 
export default new Router({
  routes: [
    { path: '/', name: 'home', component: Main },
    { path: '/main', name: 'Main', component: Main },
    { path: '/header',  name: 'Header', component: Header},
    { path: '/admin',  name: 'Admin', component: Admin}
  ]
})

在main.js中添加如下内容
在这里插入图片描述
接下里就可以开始使用路由了,在需要使用路由的地方加入以下内容

<router-link to="/">主页</router-link>     //切换到指定的组件
<router-link to="/main">主页</router-link>
<router-link to="/admin">管理页</router-link>
        
<router-view/>  //组件显示的地方

也可通过事件的方法来使用路由

methods:{
  toMain() {
    this.$router.push('./main');  //跳转到指定组件
  },
 
  //使用路由返回上一级
  goBack() {
    window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
  },
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值