使用v-for遍历数字在生产环境中并不多见,但是在开发环境中,有时候会被用到。比如我们想要快速生成10个卡片,看看页面中同时存在10个卡片时是什么样式,这个时候就可以直接使用v-for加数字来实现。
这节课,我们就来演示一下这种场景。
我们创建src/components/Demo19.vue,在这个组件中,我们要:
代码如下:
<template>
<div>
<div class="card" v-for="i in 10" :key="i">卡片-{{ i}}</div>
</div>
</template>
<style>
.card {
display: inline-block;
margin: 15px;
padding: 5px;
width: 300px;
height: 300px;
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #999;
}
</style>
接着,我们修改src/App.vue,引入Demo19.vue并进行渲染:
<script setup>
import Demo from "./components/Demo19.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
然后,我们浏览器访问:http://localhost:5173/
{
"name": "hello",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.3.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"vite": "^5.0.0"
}
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<script setup>
import Demo from "./components/Demo19.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
<template>
<div>
<div class="card" v-for="i in 10" :key="i">卡片-{{ i}}</div>
</div>
</template>
<style>
.card {
display: inline-block;
margin: 15px;
padding: 5px;
width: 300px;
height: 300px;
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #999;
}
</style>
yarn
yarn dev
浏览器访问:http://localhost:5173/