javascript - Vue.js 更新数组的内容

标签 javascript vue.js vuejs2

我有一个数组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/

相关文章:

javascript - Shopify 脚本标签

javascript - 创建多个进度圈 d3.js

laravel - vue.js 组件使用 laravel blade 作为模板

laravel - 在 v :bind inside v-for 中使用动态名称

javascript - 如何实现类似于http ://thisiskiosk. com/的可滚动圆形文字效果

javascript - iframe 中的 getElementById

vue.js - 更新的表单输入未发布新值

javascript - 为什么在这种情况下我不能过滤本地 json 文件 (vuejs2)

javascript - Vue2 watch 设置不工作

javascript - 在构造函数 Vue JS 之后推送函数将空对象传递到数组中