Vue.js 尽管通过赋值更改了数组,但列表未更新

Vue.js list not updating despite array change via assignment

我是 vue.js 的新手,但我正在尝试显示底层数组中的选项列表。但是,当基础数组更改时,列表不会 update/re-render。我将新数组直接分配给 vue 实例数据值(不使用拼接或通过索引分配)并且在控制台中如果我尝试打印出更新的基础数据(vm.clarifyings),它只是重新渲染不起作用。即使使用 vm.clarifyings.push(object) 也不会更新浏览器中的视图。

Vue 实例代码:

var vm = new Vue({
    delimiters: ['$[', '$]'], //change delimiters to allow django integration
    el: '#vue_app',
    data: {
        title: init_info.title, //page title
        active: 'presentations',
        navClass: 'nav-item nav-link', //necessary for navbar rendering
        features: features,
        question: '',
        response: '',
        feature_id: init_info.opening,
        last_feature: '',
        clarif_id: '',
        clarifyings: [],
        show_clarifying: false,
    },

相关方法更新:

fetch(url)
  .then(response => response.json())
  .then(function (data) {
      // Type out question and response
      typeWriter(data.question, 'question');
      typeWriter(data.answer, 'response');
      // Save selected option and disable previous selected option
      option_disable(vm.last_feature);
      vm.last_feature = option_ref;
      // Show clarifying questions
      vm.clarifyings = data.clarifyings;
      if (vm.clarifyings.length){
          vm.show_clarifying = true;
      }
      else {
          vm.show_clarifying = false;
      }
  }

所有这些都正常执行,只是重新渲染不起作用。如果我在初始化 Vue 实例时指定数组,它会正确呈现它根本不会更新。

HTML代码:

<select class="selectpicker" data-live-search="true" v-model="clarif_id">
        <option v-for="question in clarifyings">$[question.id$] - $[question.name$]</option> 
    </select>

Vuejs 对数组的反应性很差。请参阅官方文档:https://vuejs.org/v2/guide/reactivity.html#For-Arrays

Vue cannot detect the following changes to an array:

  • When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  • When you modify the length of the array, e.g. vm.items.length = newLength

您可以使用Vue.set(vm.clarifyings, indexOfItem, newValue)来克服这个问题。 (而不是 vm.clarifyings.push(object)

问题似乎是 bootstrap-selectpicker 干扰的结果,已通过在 vue 中使用 nextTick 功能修复,如下所示:

 if (feature_asked) {
            vm.clarifyings = data.clarifyings;
            if (vm.clarifyings.length) {
              vm.show_clarifying = true;
              vm.$nextTick(function () {
                $("#clarifying_qs").selectpicker("refresh");
              });