在 v-for 循环中将 textarea 的 v-model 绑定到 Vue.js 中的数组
Bind v-model of textarea to array in Vue.js in v-for loop
我想将数组绑定到 textarea,其中此 textarea 中的每一行都是数组中的一个元素。我不知道如何解决。我已经尝试使用 v-:change
方法结合临时 v-model
进行更新,但这很脏。
例如:
<div v-for="item, index in list">
<b-form-textarea v-model.trim="list[index]"></b-form-textarea>
</div>
结果应如下所示:
list[0] = ['row1 of textarea 1', 'row 2 of textarea 1', ...]
list[1] = ['row1 of textarea 2', 'row 2 of textarea 2', ...]
您可以将每个文本区域的输入值保存在一个对象中,这些对象收集在一个数组中。
可以通过计算 属性 处理此数组以获得您想要的结构 - split("\n")
在您的例子中。
var app = new Vue({
el: '#app',
data: {
list: [{
id: 1,
value: ""
},
{
id: 2,
value: ""
},
]
},
computed: {
listByBreaks() {
return this.list.map(e => {
return e.value.split("\n");
});
}
}
})
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<!-- Required Stylesheets -->
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />
<!-- Required scripts -->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<div id="app">
<div v-for="item in list" :key="item.id">
<b-form-textarea v-model="item.value"></b-form-textarea>
<br/>
</div>
List by breaks: {{ listByBreaks }}
</div>
我想将数组绑定到 textarea,其中此 textarea 中的每一行都是数组中的一个元素。我不知道如何解决。我已经尝试使用 v-:change
方法结合临时 v-model
进行更新,但这很脏。
例如:
<div v-for="item, index in list">
<b-form-textarea v-model.trim="list[index]"></b-form-textarea>
</div>
结果应如下所示:
list[0] = ['row1 of textarea 1', 'row 2 of textarea 1', ...]
list[1] = ['row1 of textarea 2', 'row 2 of textarea 2', ...]
您可以将每个文本区域的输入值保存在一个对象中,这些对象收集在一个数组中。
可以通过计算 属性 处理此数组以获得您想要的结构 - split("\n")
在您的例子中。
var app = new Vue({
el: '#app',
data: {
list: [{
id: 1,
value: ""
},
{
id: 2,
value: ""
},
]
},
computed: {
listByBreaks() {
return this.list.map(e => {
return e.value.split("\n");
});
}
}
})
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<!-- Required Stylesheets -->
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />
<!-- Required scripts -->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<div id="app">
<div v-for="item in list" :key="item.id">
<b-form-textarea v-model="item.value"></b-form-textarea>
<br/>
</div>
List by breaks: {{ listByBreaks }}
</div>