我有一个数组feedListBox
,我将其分配给我的提要数据对象。当我更新 feedListBox 数组时,Vue.js 没有检测到它。因此,我在 script.js 文件 myApp.fixFeedArray()
中使用 fixFeedArray
方法。它工作得很好,但我想知道是否有另一种方法可以在不使用脚本文件中的任何函数的情况下完成它。我的意思是自动。
var myApp = new Vue({
el: '#my-App',
data: {
feeds: feedListBox,
},
methods: {
fixFeedArray: function fixFeedArray() {
this.feeds = feedListBox;
}
}
});
这是更改脚本文件中 feedListBox 数组的值的函数
function searchByCategory() {
var category = $("#categoryBox").val();
var searchedCategories = feedArray.filter(function (item) {
return item.category.includes(category);
});
feedListBox = searchedCategories;
myApp.fixFeedArray();
}
最佳答案
首先,我个人会放弃 jQuery。下面是一个简单的示例,展示了如何将新数据推送到数组中,以便 Vue 对其使用react并重新渲染。如果它不是实用函数,我建议将所有操作数据的函数保留到方法对象中。
new Vue({
el: "#main",
data: {
error: null,
newText: '',
newValue: '',
categories: [{
text: "Shapes",
value: "shapes"
},
{
text: "Colors",
value: "colors"
},
{
text: "Sizes",
value: "sizes"
},
],
},
methods: {
test: function() {
if (this.newText === '' ||
this.newValue === '') {
return this.error = 'Please fill out the form!'
}
this.categories.push({
text: this.newText,
value: this.newValue,
});
return this.clear();
},
clear: function() {
this.newText = '';
this.newValue = '';
this.error = '';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="main">
{{ error }}
<ul>
<li v-for="(item, index) in categories">
{{ item.text }}
</li>
</ul>
<label>Text</label>
<input v-model="newText" type="text" />
<label>Value</label>
<input v-model="newValue" type="text" />
<button v-on:click="test">Add to Array</button>
</div>
关于javascript - Vue.js 更新数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46131250/