代码之家  ›  专栏  ›  技术社区  ›  vimuth

vue.js版axios GET中的多选更改选项

  •  0
  • vimuth  · 技术社区  · 6 年前

    this 修改包装以处理的多重选择vue.js版. 我正在尝试更改这个内部vue组件的值。这是我的密码。

    <select2-multiple :options="car_options" v-model="input.classification">
           <option disabled value="0">Select one</option>
    </select2-multiple>
    

    这是我的剧本,

    Vue.component('select2Multiple', {
      props: ['options', 'value'],
      template: '#select2-template',
      mounted: function () {
        var vm = this
        $(this.$el)
          // init select2
          .select2({ data: this.options })
          .val(this.value)
          .trigger('change')
          // emit event on change.
          .on('change', function () {
            vm.$emit('input', $(this).val())
          })
      },
      watch: {
        value: function (value) {
        alert(value);
           if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
            $(this.$el).val(value).trigger('change');
        },
        options: function (options) {
          // update options
          $(this.$el).select2({ data: options })
        }
      },
      destroyed: function () {
        $(this.$el).off().select2('destroy')
      }
    });
    
    var vm = new Vue({
        el: '#el',
        delimiters: ["[[", "]]"],
        data: {
            input: {
                classification: []
            },
        },
        created: function () {
            var vm = this;
            axios.get('http://jsonplaceholder.typicode.com/todos')
                                        .then(function (response) {
                                            $.each(response.data, function (i, item) {
                                                response.data[i].id = String(response.data[i].id);
                                                response.data[i].text = String(response.data[i].title);
                                                vm.car_options.push(response.data[i]);
                                            });
                                            vm.input.classification = ["2"];
                                        })
                                        .catch(function (error) {
                                           console.log(error);
                                        });   
        }
    });
    

    我需要得到 vm.input.分类=[“2”]默认选中 . 它不工作,没有错误信息显示。我不是vue组件方面的专家,但我觉得问题取决于vue组件。

    Here

    1 回复  |  直到 6 年前
        1
  •  0
  •   vimuth    6 年前

    最后我找到了答案。我们需要交换选项的位置和组件监视的价值。

    watch: {
        options: function (options) {
          // update options
          $(this.$el).select2({ data: options })
        },
        value: function (value) {
           if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
            $(this.$el).val(value).trigger('change');
        }
      },