VueJS 从方法访问模型

VueJS access model from method

在 VueJS 中,我根据用户操作设置模型数据。我想通过更新元素的方法访问模型。

在下面的代码中,当用户更改第一个 select 列表时,我想更新第二个 select 列表以显示第一个列表的 ID 属性。因为它是上层列表工作正常但下层列表 id 属性 不会在上层列表更改时更新:

<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
</head>
<body>
        <div id="editor">
            <form id="query" methods="GET">
            <div id="form_container" class="row">
                        <div class="form-group">
                            <label for="choice-selector">Choices</label>
                            <select class="form-control" id="choice-selector" v-model="choice_id" v-on:change="refreshOptions">
                              <option v-for="item in choices" v-bind:value="item.id">
                                {{ item.name }}
                              </option>
                            </select>
                            <span>Current choice id: {{ choice_id }}</span>
                            <br>
                            <label for="option-selector">Options</label>
                            <select class="form-control" id="option-selector" v-model="option_id" >
                                <option v-for="item in options" v-bind:value="item.id">
                                    {{ item.name }}
                                </option>
                            </select>
                            <span>Current option id: {{ option_id }}</span>
                        </div>
            </div>
        </div>

    <script>
    let index = 0;
    new Vue({
        el: '#editor',
        data: {
            choice_id: '1',
            choices: [
              { id: '1', name: 'Choice A' },
              { id: '2', name: 'Choice B' },
              { id: '3', name: 'Choice C' }
            ],
            option_id: '1',
            options: [
            ]
          },
        ready: function startFetch() {
          this.refreshOptions();
        },
        methods: {
          refreshOptions: function refreshOptionList() {
            console.log(">>refreshOptionList() index:" + index);
            const vm = this;
            const newOptions = [{ id: index, name: 'Option based on choices list id: ' + vm.choice_id }];
            vm.$set('options', newOptions);
            index += 1;
          }
        },
      });
    </script>
</body>
</html>

有什么想法吗?

在 Vue 2.x vm.$set is an alias for Vue.set 中它需要 3 个参数:targetkeyvalue 所以你应该这样使用它:

vm.$set(this, 'options', newOptions);

或者您可以将 newOptions 分配给 this.options

this.options = newOptions;

工作示例:https://plnkr.co/edit/lFDm7wxb56h81EAwuUNc