Vue中路由的正确注册和路由跳转页面
安装router
npm i vue-router
配置两个组件login.vue,homePage.vue
1.设置路由器(管理路由):在src目录下,新建一个文件夹router,专门放路由器(index.js)
Tip:将默认路径修改是把<router-view放在app.vue中能实现的关键
访问http://127.0.0.1:8080/即访问http://127.0.0.1:8080/login
将默认路径显示出login组件
//引入VueRouter
import VueRouter from "vue-router"
//引入路由组件
import login from '../pages/login'
import homePage from '../pages/homePage'
//暴露路由
export default new VueRouter({
routes: [
{
//将默认路径显示出login组件
//访问http://127.0.0.1:8080/即访问http://127.0.0.1:8080/login
path: '/',
component: login
},
{
path: '/login',
name: 'login',
component: login
},
{
path: '/homePage',
name: 'homePage',
component: homePage
}
]
})
2.在main.js配置路由
import Vue from 'vue'
import App from './App.vue'
//引入路由
import router from './router/index.js'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//关闭生产模式给出的提示
Vue.config.productionTip = false
new Vue({
render: h => h(App),
//将路由注册到根实例中
router
}).$mount('#app')
3.在app.vue中使用路由<router-view放在app.vue中
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
*{
padding: 0px;
margin: 0px;
}
</style>
4.在以上基础上,实现登陆页面与主页的跳转this.$router.push('/homePage')
要正确注册VueRouter才可以使用$router
sendInfo(){
axios.post('http://localhost:8081/api/login', {
data: {
username: this.username,
password: this.password
}
}, {
//将传输数据定为json格式
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
console.log(res.data)
this.$router.push('/homePage')
}).catch((error) => {
console.log(error);
});
}