vue实现添加div
动态添加 div 的方法
模板中使用 v-for
通过数据驱动视图,在模板中使用 v-for 循环渲染多个 div:

<template>
<div v-for="(item, index) in divList" :key="index">
{{ item.content }}
</div>
<button @click="addDiv">添加Div</button>
</template>
<script>
export default {
data() {
return {
divList: []
}
},
methods: {
addDiv() {
this.divList.push({ content: `新Div ${this.divList.length + 1}` })
}
}
}
</script>
使用 ref 操作 DOM 通过 Vue 的 ref 直接操作 DOM 元素:
<template>
<div ref="container"></div>
<button @click="appendDiv">添加Div</button>
</template>
<script>
export default {
methods: {
appendDiv() {
const newDiv = document.createElement('div')
newDiv.textContent = '动态添加的Div'
this.$refs.container.appendChild(newDiv)
}
}
}
使用渲染函数 (render function) 通过 JavaScript 的渲染函数动态创建元素:
<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
- 直接操作 DOM 可能违反 Vue 的数据驱动原则
- 动态添加的元素同样受 Vue 响应式系统管理
- 复杂场景建议使用组件化方式实现
以上方法可根据具体需求选择,数据量较大时推荐使用 v-for 方式,需要精细控制 DOM 时可采用 ref 或渲染函数。







