首先搭建好vue框架后
在src文件夹下创建一个router文件夹,router文件夹下创建router.js文件
router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router) //让vue使用Router
const router = [
{
path: "/index",
component: ()=>import("../components/index.vue")
},
{
path:"/",
component: ()=>import("../components/login.vue")
},
{
path:"/login",
component: ()=>import("../components/login.vue")
}
];
var rou =new Router(
{
routes: router
})
rou.beforeEach((to,from,next)=>{
if(to.path!=="/login"){
if(localStorage.getItem("islogin")=="true"){
return next();
}else{
return next("/login")
}
}
return next();
})
export default rou;
在components文件夹下创建index.vue文件和login.vue文件
index.vue
<template>
<div class="index">
{{mess}}
</div>
</template>
<script>
export default {
data(){
return{
mess:"首页",
}
},
}
</script>
<style>
.index{
font-size: 30px;
text-align: center;
}
</style>
login.vue
<template>
<div>
<p><input type="text" v-model="name"></p>
<p><input type="text" v-model="pass"></p>
<button @click="yz">登录</button>
</div>
</template>
<script>
export default {
data(){
return{
name:"",
pass:""
}
},
methods:{
yz(){
if(this.name=="zs"){
if(this.pass=="123"){
alert("登录成功");
localStorage.setItem("islogin","true");
this.$router.replace("/index")
}else{
alert("密码错误");
}
}else{
alert("用户名错误");
}
}
}
}
</script>
<style>
</style>
最后App.vue改为
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
</style>
|