vue 定义数组并循环添加字符串
时间: 2023-08-13 22:05:55 浏览: 197
可以使用 Vue 的数据绑定语法和循环指令来实现。
首先在 Vue 的 data 中定义一个数组:
```
data() {
return {
strings: []
}
}
```
然后在模板中使用 v-for 指令循环渲染数组中的字符串,并使用 v-model 指令将输入框的值与 data 中的数组绑定起来:
```
<template>
<div>
<input type="text" v-model="newString">
<button @click="addString">添加</button>
<ul>
<li v-for="(str, index) in strings" :key="index">{{ str }}</li>
</ul>
</div>
</template>
```
最后在 methods 中定义 addString 方法,用于将输入框中的字符串添加到数组中:
```
methods: {
addString() {
this.strings.push(this.newString)
this.newString = ''
}
}
```
完整代码示例:
```
<template>
<div>
<input type="text" v-model="newString">
<button @click="addString">添加</button>
<ul>
<li v-for="(str, index) in strings" :key="index">{{ str }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
strings: [],
newString: ''
}
},
methods: {
addString() {
this.strings.push(this.newString)
this.newString = ''
}
}
}
</script>
```