响应式小例子
记着玩,通过屏幕的宽度改变导航栏的位置
代码如下:
<template>
<div id='index'>
<div :class="{left:isLeft,top:!isLeft}">
<a-menu
@click="handleClick"
:defaultSelectedKeys="['1']"
:openKeys.sync="openKeys"
:mode="mode"
:class="{left:isLeft,top:!isLeft}"
>
<a-sub-menu key="sub2" @titleClick="titleClick">
<span slot="title"><a-icon type="appstore"/><span>子路由</span></span>
<a-menu-item key="1">
<router-link to="/index/foo">
子路由Foo
</router-link>
</a-menu-item>
<a-menu-item key="2">
<router-link to="/index/bar">
子路由bar
</router-link>
</a-menu-item>
<a-sub-menu key="sub3" title="路由别名">
<a-menu-item key="/bar" title="子路由bar别名,允许直接访问,注意url是没有index的">
子路由bar别名
</a-menu-item>
</a-sub-menu>
</a-sub-menu>
<a-sub-menu key="sub4">
<span slot="title"><a-icon type="setting"/><span>路由对比</span></span>
<a-menu-item key="/my">
子路由my,路由配置带/
</a-menu-item>
<a-menu-item key="/index/hehe">
子路由my别名,前面有index
</a-menu-item>
</a-sub-menu>
</a-menu>
</div>
<div :class="[isLeft ? 'right' : 'bottom']">
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
openKeys: ['sub2'],
mode: 'inline',
isLeft: true
}
},
methods: {
pushRouter (name) {
this.$router.push({ path: name })
},
handleClick (e) {
console.log('按钮click', e)
if (isNaN(e.key)) {
this.$router.push({ path: e.key })
}
},
titleClick (e) {
console.log('titleClick', e)
}
},
watch: {
openKeys (val) {
console.log('openKeys', val)
}
},
// 钩子函数
mounted () {
//获取屏幕宽度设置样式
const that = this
window.onresize = () => {
return (() => {
var width = window.screenWidth = document.body.clientWidth
if (width <= 768) {
that.mode = 'horizontal'
that.isLeft = false
} else {
that.mode = 'inline'
that.isLeft = true
}
})()
}
}
}
</script>
<style lang='less' scoped>
@leftWidth: 256px;
@topHeight: 50px;
#index {
width: 100%;
height: 100vh;
.left {
height: 100vh;
width: @leftWidth;
float: left;
}
.right {
/*calc在less中计算出错的解决方法*/
width: calc(~"100%" - @leftWidth);
padding: 20px;
float: right;
}
.top {
width: 100%;
height: @topHeight;
}
.bottom {
width: 100%;
height: calc(~"100%" - @topHeight);
padding: 10px;;
}
}
</style>
路由配置
alias: '/bar'
这个别名使得可以通过
http://localhost:8080/bar
访问和http://localhost:8080/index/bar
一样的页面。
同样的,http://localhost:8080/my
和 http://localhost:8080/index/hehe
访问相同的页面
{
path: '/index',
name: 'index',
redirect: '/index/foo',
component: () => import('./views/routerTest/index.vue'),
children: [
{
// 当 /test/foo 匹配成功,
// foo 会被渲染在 User 的 <router-view> 中
path: 'foo',
component: foo
},
{
path: 'bar',
component: bar,
alias: '/bar'
},
{
path: '/my',
component: require('@/components/routerTest/my').default,
alias: 'hehe'
}
]
},
```