# tg-aspect-ratio
# 介绍
项目中偶尔会遇到页面上某些元素固定比例显示的设计,常见的比如一个九宫格图片,每个图片需要显示成正方形。
这时候就可以使用本组件,快速去布局。
使用的时候只需要传入宽高的比例即可。
# 安装
npm i tg-aspect-ratio
# 用法
import Vue from 'vue'
import TgAspectRatio from 'tg-aspect-ratio'
import 'tg-aspect-ratio/dist/index.css'
Vue.use(TgAspectRatio)
<tg-aspect-ratio w="1" h="1">
...
</tg-aspect-ratio>
# 示例
# 基础用法
通过给组件的父元素设置一个宽度,即可控制组件的大小,比如你想要一个100px * 100px的元素,那么就给组件的父元素宽度设为100px即可。
{ "width": 0, "height": 0 }
Hello World
<template>
<div>
<p>通过给组件的父元素设置一个宽度,即可控制组件的大小,比如你想要一个100px * 100px的元素,那么就给组件的父元素宽度设为100px即可。</p>
<p>
<button @click="set(1,1)">1:1</button>
<button @click="set(2,1)">2:1</button>
<button @click="set(4,3)">4:3</button>
<input rows="5" v-model="text" />
<span>{{size}}</span>
</p>
<div class="w-100">
<tg-aspect-ratio ref="ar" :w="w" :h="h">{{text}}</tg-aspect-ratio>
</div>
</div>
</template>
<script>
export default {
data () {
return {
w: 1,
h: 1,
text: 'Hello World',
size: {
width: 0,
height: 0,
}
}
},
watch: {
w () { this.getSize() },
h () { this.getSize() },
},
mounted () {
this.getSize()
},
methods: {
set (w, h) {
this.w = w
this.h = h
},
getSize () {
this.$nextTick(function () {
let el = this.$refs.ar.$el
this.size = {
width: el.offsetWidth,
height: el.offsetHeight,
}
})
}
}
}
</script>
<style>
.w-100 {
width: 100px;
}
.tg-aspect-ratio {
color: white;
background-color: black;
}
</style>
# 九宫格布局
1
2
3
4
5
6
7
8
9
<template>
<div class="mobile">
<div class="container">
<div class="item" v-for="n in 9">
<tg-aspect-ratio w="1" h="1">{{n}}</tg-aspect-ratio>
</div>
</div>
</div>
</template>
<style>
.mobile {
width: 375px;
height: 667px;
border: 1px solid black;
}
.container {
display: flex;
flex-wrap: wrap;
}
.item {
width: 33.3333%;
}
.item:nth-child(odd) .tg-aspect-ratio {
color: black;
background-color: white;
}
</style>
# 参数
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
w | 宽度 | Number,String | 1 |
h | 高度 | Number,String | 1 |
组件会根据传入的宽高,自动计算出一个比例。