目录:
vue 路由
整合第三方路由
--------------------------------
对于大多数单页面应用,都推荐使用官方支持的vue-router库。更多细节可以看vue-router文档。
如果只需要非常简单的路由而不需要引入整个路由库,可以动态渲染一个页面级的组件:
demo:
<h4>使用 h5 实现前端路由</h4>
<ul>
<li> <a onclick="home()">首页</a></li>
<li> <a onclick="message()">消息</a></li>
<li> <a onclick="mine()">我的</a></li>
</ul>
<div id="showContent" style="height:240px;width:200px;background-color:red">
home
</div>
<script type="text/javascript">
function home() {
// 添加到历史记录栈中
history.pushState({name:'home',id:1},null,"?page=home#index")
showCard('home')
};
function message() {
history.pushState({name:'message',id:2},null,"?page=message#haha")
showCard('message')
}
function mine(){
history.pushState({
id:3,
name:'mine'
},null,"?name=tigerchain&&sex=man")
showCard('mine')
}
整合第三方路由:
hash路由:
demo:
<script type="text/javascript">
//自定义一个路由规则
function CustomRouter(){
this.routes = {};
this.curUrl = '';
this.route = function(path, callback){
this.routes[path] = callback || function(){};
};
this.refresh = function(){
if(location.hash.length !=0){ // 如果 hash 存在
this.curUrl = location.hash.slice(1) || '/';
if(this.curUrl.indexOf('/')!=-1){ //这里粗略的把 hash 过滤掉
this.routes[this.curUrl]();
}
}
};
this.init = function(){
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
}
还有一种vue -cli 的路由:
// 定义一个 Mine 组件
var Mine = Vue.extend({
data() {
return {
title:'我的界面',
}
},
template:'<div style="height:100px;width:100px;background:orange">'+
'<span>{{title}}--取得路由参数:{{$route.params.id}}</span>'+
'</div>'
})
// 声明路由规则
const routes = [
//给一个默认的路由,默认显示 Main 组件
{
path:'/',component:Main
},
{
path:'/main',component:Main
},
{
path:'/message',component:Message
},
{
path:'/mine/:id',component:Mine
}
]
// 全局注册组件 组件的别名要是小写,否则会报错
// Vue.component('home', Main)
// Vue.component('message', Message)
// Vue.component('mine', Mine)
// 创建 router 实例
const router = new VueRouter({
routes // 就相当于是 routes:routes
})