'How to preload text into text area in v-for loop(vue)?
I am struggling on something that I thought would first be easy to solve.
Imagine a page loading with multiple text areas as:
<div v-for="(item, index) in articles" class="bg-white shadow-lg sm:rounded-lg gap-3 mt-2" :key="index">
<h1>{{item.title}}</h1>
<textarea v-model="form5.fullArticle" :value="item.paragraph" id="topicDescription" :rows="5" cols="80">
</textarea>
</div>
When the v-for
loop runs, I am getting a lot of item.paragraph
and item.title
data and would like to save them to an array.
Problem 1:
I cannot work out how to preload {{item.paragraph}}
into a text area. It looks like :value="" is not accepted. and I also tried this <textarea>{{item.paragraph}}</textarea>
but no luck (I did not expect this behavior).
Problem 2:
How can I save in my v-for
the {item.title}}
and {{item.paragraph}}
into a new array (but group them together).
Any idea please?
Thanks!
Solution 1:[1]
Try to use just v-model (it is the shortcut of :value="text"
@input="event => text = event.target.value"
) :
const app = Vue.createApp({
data() {
return {
articles: [{id: 1, title: "AAA", paragraph: "aaa"}, {id: 2, title: "BBB", paragraph: "bbb"},{id: 3, title: "CCC", paragraph: "ccc"}],
newArray: []
};
},
methods: {
saveArt(item) {
const found = this.newArray.find(a => a.id === item.id)
if (!found) this.newArray.push(item)
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(item, index) in articles" class="bg-white shadow-lg sm:rounded-lg gap-3 mt-2" :key="index">
<h5>{{item.title}}</h5>
<textarea v-model="item.paragraph" id="topicDescription" :rows="3" cols="30">
</textarea>
<button @click="saveArt(item)">Add</button>
</div>
<p>new array</p>
{{ newArray }}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |