繁体   English   中英

VueJS 从方法访问模型

[英]VueJS access model from method

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

在下面的代码中,当用户更改第一个选择列表时,我想更新第二个选择列表以显示第一个列表的 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.$setVue.set的别名,它有 3 个参数: targetkeyvalue ,所以你应该像这样使用它:

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

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

this.options = newOptions;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM