Vue3 实现登录跳转页面和内部跳转页面(加载组件)
点击登录按钮即跳转到新页面,而不是在当前页面加载组件
App.Vue:
<script>
export default {
data(){
return{}
}
}
</script>
<template>
// 必须加上router-view,否则会显示空白页面
<router-view></router-view>
</template>
<style>
</style>
main.js:
import './assets/main.css'
import App from './App.vue'
import { createApp } from 'vue'
import router from './router'
import ElementUI from 'element-plus'
import 'element-plus/theme-chalk/index.css'
const app = createApp(App)
app.use(router)
app.use(ElementUI)
app.mount('#app')
index.js:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../components/home.vue'
import IndexView from '../components/Index.vue'
import Login from '../components/Login.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path:'/index',
name:'index',
component:IndexView
},
{
path:'/',
alias:'/login', // 别名
component:Login
}
]
})
export default router
Login.Vue:
<!--<script>-->
<!--export default {-->
<!-- data(){-->
<!-- return {}-->
<!-- },-->
<!-- methods:{-->
<!-- login(){-->
<!-- this.$router.push('/index')-->
<!-- }-->
<!-- }-->
<!--}-->
<!--</script>-->
<script setup>
import {RouterLink, RouterView, useRouter} from 'vue-router'
const router = useRouter()
function login() {
router.push('/index');
}
</script>
<template>
<div>
<button @click.prevent="login">确认</button>
</div>
</template>
<style scoped>
</style>
index.Vue:
<script setup>
</script>
<template>
<h1>Hello world!</h1>
<router-view></router-view>
</template>
<style scoped>
</style>
在内部跳转页面:
- 方法一:在App.vue中补充函数
// 或写为<script setup>
<script setup>
import {RouterLink, RouterView, useRouter} from 'vue-router'
const router = useRouter()
function goto() {
router.push('/home');
}
</script>
<script>
export default {
data(){
return {}
},
methods:{
goto(){
this.$router.push('/home')
}
}
}
</script>
<template>
<h1>首页</h1>
<el-button @click="goto">登录</el-button>
<!-- <router-link to="/login" tag="button">登录</router-link>-->
<RouterView/>
</template>
路由:
// path:'/home',
// name:'home',
// component:HomeView