1. Definition and usage
The calc() function is used to dynamically calculate the length value
- A space is required before and after the operator, for example: width: calc(100%-10px);
- Any length value can be calculated using the calc() function;
- The calc() function supports "+ ","-", "* "," / "operations;
- The calc() function uses standard precedence rules for mathematical operations;
2. Use calc to calculate length and pass parameters
Requirements:
According to the length of the array returned by the server to calculate the width of the element and be compatible when the screen width changes, we can consider using calc to calculate the length and pass parameters.
2.1 Complete code
<template>
<div>
<div class="home">
<div class="test1" v-for="item in resArr" :key="item" :style="div1Width()"></div>
</div>
<div class="test2" :style="div2Width()"></div>
</div>
</template>
<script>
export default {
data() {
return {
resArr:[1,3,5,7] // 模拟服务端返回数据
};
},
methods: {
div1Width(){
let arrLength = this.resArr.length;
return `width: calc((100% - 200px)/${
arrLength});`
},
div2Width(){
let arrLength = this.resArr.length*100 + 'px';
return `width: calc(100% - ${
arrLength});`
},
}
};
</script>
<style lang="stylus" scoped>
.home{
display:flex;
justify-content: space-around;
.test1{
height:20px;
background-color: pink;
}
}
.test2{
margin-top:30px;
height:20px;
background-color: red;
}
</style>
2.2 Effect