面试官问:一个页面中,居中竖直排列三个正方形,颜色分别为红、黄、绿; 其中正方形由组件提供,组件接收参数来显示不同的颜色,默认为黑色; 请写出页面和组件代码。
效果图:
v3脚手架实现:
<!-- HelloWorld.vue -->
<template>
<div :style="{ backgroundColor: color }" class="square"></div>
</template>
<script>
export default {
props: {
color: {
type: String,
default: "black"
}
}
};
</script>
<style scoped>
.square {
width: 100px;
height: 100px;
margin-bottom: 20px;
}
</style>
app.vue
<template>
<div id="app">
<Square color="red" />
<Square color="yellow" />
<Square color="green" />
</div>
</template>
<script>
import Square from "@/components/HelloWorld.vue";
export default {
components: {
Square
}
};
</script>
<style>
#app {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
</style>
这样就满足了面试官题目的要求,然后紧接着在这个图形基础上面面试官问:页面中顶部添加一个按钮,每次点击后页面中正方形个数变为1-10随机,每个正方形的颜色为随机色。
效果如图
然后我该代码如下
<!-- HelloWorld.vue -->
<template>
<div class="hello">
<div :style="{ background:color}" class="square"></div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
color:{
type:String,
default:'black'
}
},
}
</script>
<style scoped>
.square{
width: 100px;
height: 100px;
margin: 10px;
display: inline-block;
}
</style>
app.vue里边代码是:
<template>
<div class="container">
<!-- <img alt="Vue logo" src="./assets/logo.png"> -->
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<button @click="randomSquares">随机生成正方形颜色个数</button>
<div class="Rsquares">
<HelloWorld v-for="(color , index ) in squareColors" :key="index" :color="color" />
</div>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
data(){
return {
squareColors:[]
}
},
methods: {
randomSquares(){
const numSquares = Math.floor(Math.random() * 10 ) + 1
this.squareColors = Array.from({ length: numSquares}, () => this.getRandomColor())
},
getRandomColor(){
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++ ){
color += letters[Math.floor(Math.random() * 16 )]
}
return color
}
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
这样就可以实现了题目要求
最后面试官提出第三个要求 把图中正方形变成三角形 效果如图
直接找到找到HelloWorld组件中css中把正方形改成三角行
<style scoped>
.square{
width: 0;
height: 0;
border-left: 50px solid white;
border-right: 50px solid white;
border-bottom: 87px solid transparent;
margin: 1px;
display: inline-block;
}
</style>
然后笔试题结束,面试官表示比较满意,然后就问别的问题了,希望分享出来可以帮到还在找工作的你