<template> <div class="word-container"> <div class="word" v-for="(word, index) in words" :key="index">{{ word }}</div> </div> </template> <script> export default { data() { return { words: ['Hello', 'World', 'Vue'] } } } </script> <style> .word-container { display: flex; flex-wrap: wrap; justify-content: center; } .word { margin: 10px; padding: 10px; font-size: 24px; font-weight: bold; background-color: #f0f0f0; border-radius: 5px; text-align: center; } </style>添加一个输入款
时间: 2024-03-26 07:36:21 浏览: 65
好的,你可以在模板中添加一个输入框,然后通过`v-model`指令将输入框的值绑定到`words`数组中,代码如下所示:
```html
<template>
<div class="word-container">
<div class="word" v-for="(word, index) in words" :key="index">{{ word }}</div>
<input type="text" v-model="newWord" placeholder="请输入新单词">
<button @click="addWord">添加</button>
</div>
</template>
<script>
export default {
data() {
return {
words: ['Hello', 'World', 'Vue'],
newWord: ''
}
},
methods: {
addWord() {
if (this.newWord) {
this.words.push(this.newWord.trim())
this.newWord = ''
}
}
}
}
</script>
<style>
.word-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.word {
margin: 10px;
padding: 10px;
font-size: 24px;
font-weight: bold;
background-color: #f0f0f0;
border-radius: 5px;
text-align: center;
}
</style>
```
以上代码中,在模板中添加了一个`<input>`和一个`<button>`,然后通过`v-model`指令将输入框的值绑定到`newWord`变量中,绑定按钮的`click`事件,当按钮被点击时调用`addWord`方法,将新单词添加到`words`数组中,并清空输入框的值。
阅读全文