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

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

安装路由

npm install vue-router

创建router.js与mian.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("/");
  },
}

 

欢迎访问本人个人网站:V1.0版本  https://www.dzyong.com

                                       V2.0版本(开发中)  http://39.108.168.243:8005

发布了64 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/DengZY926/article/details/86521579