vue实现添加div
在 Vue 中动态添加 div 元素
使用 v-for 指令动态渲染 div
通过 v-for 可以基于数组数据动态生成多个 div 元素。在模板中绑定数组数据,Vue 会自动遍历数组并为每个元素创建对应的 div。
<template>
<div>
<div v-for="(item, index) in items" :key="index">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ text: 'Div 1' },
{ text: 'Div 2' }
]
}
}
}
</script>
通过方法动态添加 div 到数组
通过调用方法修改数据数组,Vue 的响应式系统会自动更新 DOM。使用 push 方法向数组添加新元素,触发视图更新。
<template>
<div>
<div v-for="(item, index) in items" :key="index">
{{ item.text }}
</div>
<button @click="addDiv">添加 Div</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ text: 'Div 1' },
{ text: 'Div 2' }
]
}
},
methods: {
addDiv() {
this.items.push({ text: `Div ${this.items.length + 1}` })
}
}
}
</script>
使用 $refs 和原生 DOM 操作
在需要直接操作 DOM 时,可以通过 $refs 获取元素引用,然后使用原生 DOM API 添加 div。这种方式适用于需要更精细控制 DOM 的场景。
<template>
<div>
<div ref="container"></div>
<button @click="insertDiv">插入 Div</button>
</div>
</template>
<script>
export default {
methods: {
insertDiv() {
const newDiv = document.createElement('div')
newDiv.textContent = '新添加的 Div'
this.$refs.container.appendChild(newDiv)
}
}
}
</script>
使用渲染函数 (Render Function)
对于复杂场景,可以使用 Vue 的渲染函数动态创建元素。通过 h 函数创建虚拟节点,实现更灵活的 DOM 操作。
<script>
export default {
data() {
return {
divCount: 0
}
},
render(h) {
const children = []
for (let i = 0; i < this.divCount; i++) {
children.push(h('div', `动态 Div ${i + 1}`))
}
return h('div', [
...children,
h('button', {
on: {
click: () => this.divCount++
}
}, '添加 Div')
])
}
}
</script>
注意事项
- 使用
v-for时始终为每个元素提供唯一的key属性,帮助 Vue 高效更新 DOM - 优先使用数据驱动的方式(如修改数组)而非直接操作 DOM
- 在组件销毁时,使用原生 DOM 操作添加的元素需要手动清理
- 渲染函数适合高级用法,简单场景建议使用模板语法







