1.npm install vue-router@3.5.0 下载路由
如果报错,请查看node是否有问题
2..配置路由,在src路径下面新建一个route文件夹,然后新建一个index.js,例如:
//route->index.js内容
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入页面
import Allpages from '../views/allpages.vue'
import Job from '../views/job.vue'
Vue.use(VueRouter);
let router = new VueRouter({
routes: [
{
//路由匹配路径
path: "/",
//路由名称
name:"allpages",
//定义路径所对应的组件(当你访问当前路径是要展示哪个组件)
component: Allpages
},
{
path: "/job",
component: Job
}// {
// path: '/about',
// name: 'about',
//路由懒加载,路由的另一种写法
// component: () => import(@/views/AboutView.vue)
// },
]
})
// 导出路由
export default router
3.在main.js里面引入注册路由
//main.js里面的内容
//引入vuejs
import Vue from 'vue'
//引入app跟组件
import App from './App.vue'
新增 //引入路由
import router from '../src/route/index.js'
//设置模式
Vue.config.productionTip = false
// 创建vue实例
new Vue({
//注册路由
router,
新增 // 将组件渲染
render: h => h(App),
}).$mount('#app')
//将vue实例挂载到#app标签上
4.在app.vue显示,用来展示路由 所匹配的组件<router-view></router-view>
<template>
<div id="app">
{{ num }}
<button @click="num++">++</button>
新增 <router-view></router-view>
<!-- 使用组件 -->
</div>
</template>
<script>
//引入组件
export default {
name: "App",
data() {
return {
num: 0,
};
},
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>
5.如果报错可能是eslin的问题,把eslin关一下 ,在vue.config.js里面
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
ERROR in [eslint]
D:\AAA重新加油\day6\vuedome1\src\views\allpages.vue
1:1 error Component name "allpages" should always be multi-word vue/multi-word-component-names
D:\AAA重新加油\day6\vuedome1\src\views\job.vue
1:1 error Component name "job" should always be multi-word vue/multi-word-component-names
✖ 2 problems (2 errors, 0 warnings)
webpack compiled with 1 error
**解决办法:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
//解决约束报错问题
lintOnSave: false
})
6.路由跳转
<router-link to="路径名称"></router-link>
gohome(){
this.$route.puth({
path:"/home"
})
}