用vue写个杨辉三角形
时间: 2023-11-20 17:36:08 浏览: 94
杨辉三角形的visual basic制作代码
好的,我可以帮你编写一个用Vue编写的杨辉三角形代码,如下所示:
<template>
<div class="triangle">
<div class="row" v-for="(row, index) in triangle" :key="index">
<span v-for="num in row" :key="num">{{ num }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
triangle: []
}
},
mounted() {
this.generateTriangle(10) // 在这里设置三角形的行数
},
methods: {
generateTriangle(rows) {
let triangle = []
for (let i = 0; i < rows; i++) {
let row = []
for (let j = 0; j <= i; j++) {
if (j === 0 || j === i) {
row.push(1)
} else {
let prevRow = triangle[i - 1]
row.push(prevRow[j - 1] + prevRow[j])
}
}
triangle.push(row)
}
this.triangle = triangle
}
}
}
</script>
<style scoped>
.triangle {
display: flex;
flex-direction: column;
text-align: center;
}
.row {
display: flex;
justify-content: center;
margin-bottom: 5px;
}
span {
padding: 0 10px;
font-size: 16px;
font-weight: bold;
}
</style>
阅读全文