一、概念
1、SPA是什么:
单页Web应用(single page application,SPA),就是只有一个Web页面的应用,
是加载单个HTML页面,并在用户与应用程序交互时动态更新该页面的Web应用程序
2、vue路由的优点和缺点
优点:
减少了请求体积,加快页面响应速度,降低了对服务器的压力
更好的用户体验,让用户在web app感受native app的流畅
缺点:
不利于 SEO
使用浏览器的前进,后退键的时候会重新发送请求,没有合理利用缓存
单页面无法记住之前滚动的位置,无法在前进,后退的时候记住滚动的位置
二、SPA实现思路
1、 引入依赖库
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.1.4/vue-router.js"></script>
2 、创建自定义组件,例如:Home和Abort组件
const Home = Vue.extend({});
注1:extend是构造一个组件的语法器. 你给它参数,他给你一个组件,然后这个组件
你可以作用到Vue.component这个全局注册方法里,也可以在任意vue模板里使用car组件
注2:也可以用以前的方式创建和获得组件,效果也是一样的
Vue.component("button-counter", {...});//创建组件
var ButtonCounter = Vue.component('button-counter');//获得组件
3 、定义路由(即路线),
var routes = [{path: ‘/about’,component: About}];
注1:根路径“/”
4、 创建路由器实例,然后传 routes
配置
const router = new VueRouter({routes:routes});
注1:route和router的区别
route:路线
router:路由器
路由器中包含了多个路线
5、 创建和挂载根实例
var vm = new Vue({router: router}).$mount(’#app’);
三、代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vue之路由</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.1.4/vue-router.js"></script>
</head>
<body>
<div id="app">
<h2>{{title}} {{ts}}</h2>
<div>
<router-link to="/home" replace>首页</router-link>
<router-link to="/about">关于我们</router-link>
</div>
<div>
<button @click="prev">前一页</button>
<button @click="next">后一页</button>
<button @click="push">返回顶部</button>
</div>
<div>
<router-view></router-view>
</div>
</div>
</body>
<script type="text/javascript">
//注册自定义组件
const Home=Vue.extend({
template:'<div><h2>Home</h2><div>Home页面的主要内容</div></div>'
});
const About=Vue.extend({
template:'<div><h2>About</h2><div>About页面的主要内容</div></div>'
});
//定义路由(路径)
var routes=[
{name:'home',path:'/home',component:Home},
{path:'/about',component:About}
];
//定义路由器
const router=new VueRouter({routes:routes});
var vm=new Vue({
//el:'#app',
data:function(){
return{
title:'Hello Vue!',
ts:new Date().getTime()
}
},
router:router,
methods:{
prev:function(){
this.$router.go(-1);
},
next:function(){
this.$router.go(1);
},
push:function(){
this.$router.push({
name:'home'
});
}
}
}).$mount('#app');
</script>
</html>