簡體   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