【问题标题】:Vue.js list not updating despite array change via assignment尽管通过赋值更改了数组,但 Vue.js 列表没有更新
【发布时间】:2020-09-13 19:35:21
【问题描述】:

我是 vue.js 的新手,但我正在尝试显示来自底层数组的选项列表。但是,当底层数组更改时,列表不会更新/重新渲染。我将新数组直接分配给 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>

【问题讨论】:

  • 你在哪里使用 fetch?还有为什么你没有把它设置在created钩子里?

标签: javascript vue.js v-for


【解决方案1】:

这个问题似乎是由于 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");
              });

【讨论】:

    【解决方案2】:

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

    Vue 无法检测到数组的以下更改:

    • 当您直接使用索引设置项目时,例如vm.items[indexOfItem] = newValue
    • 当您修改数组的长度时,例如vm.items.length = newLength

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

    【讨论】:

    • 工作就像一个魅力!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2020-12-25
    • 2021-02-05
    相关资源
    最近更新 更多