一、当用户登录后主页显示用户的用户名
login.vue
index.js
main.vue
结果:
二、路由模式(mode:‘history’)
路由模式有两种:
hash(默认):路径代#符号,如http://localhost/#/login
history:路径不带#符号,如http://localhost/login
export default {
//路由模式
mode:‘’history’,
name: "Login",
data(){
return{
form: {
username:'',
password:''
},
三、处理404
3.1新建一个vue
NotFound.vue
<template>
<div>
<h1>404,你的页面走丢了</h1>
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
index.js
import NotFound from '../views/NotFound'
{
path: '*',
component: NotFound
}
四、路由钩子与异步请求
beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
在钩子函数中使用异步请求
4.1、安装Axios
cnpm install axios -s
4.2、main.js 引用Axios
import axios from ‘axios’;
import VueAxios from ‘vue-axios’;
Vue.use(VueAxios,axios);
4.3引入axios,
data.json
{
"name": "vue",
"url": "https://www.bilibili.com/",
"page": 1,
"isNonProfit": true,
"address": {
"street": "xxx",
"city": "北京",
"country": "中国"
},
"links": [
{
"name": "bilbili",
"url": "https://space.bilbili.com/95256449"
},
{
"name": "狂胜说java",
"url": "https://blog.kuangstudy.com"
},
{
"name": "百度",
"url": "https://www.baidu.com/"
}
]
}
npm run dev
Profile.vue
<template>
<!--所有的元素,必须不能在根节点下-->
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
name: "UserProfile",
props:['id'],
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前");//加载数据
next(vm =>{
vm.getDate();//进入路由之前执行getDat方法
});
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入路由之后");
next();
},
methods:{
getDate: function () {
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (response){
console.log(response)
})
}
}
}
</script>
<style scoped>
</style>