2017-03-06 13 views
1

VueJSでは、ユーザーの操作に基づいてモデルデータを設定しています。私は要素を更新するメソッドからモデルにアクセスしたいです。VueJSアクセスモデルからメソッド

以下のコードでは、ユーザーが最初の選択リストを変更したときに、2番目の選択リストを更新して、最初のリストのidプロパティを表示します。それは、上のリストは、[OK]を動作しますが、下のリストの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

+0

'vm.options'にアクセスできませんか?あなたはフィドルを作ることができますか? – Saurabh

+1

@Saurabh私はコードをhtmlに埋め込まれたvueに変更したので、コードをhtmlページに貼り付けてブラウザで開くことができます。 refreshOptionsメソッドからchoicesリストのidプロパティまたはchoice_idプロパティにアクセスすることはできません。 –

答えて

1

Vue.setの別名であり、それは3つのパラメータとりますので、あなたはこのようにそれを使用する必要がありますtargetkeyvalueを:

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

それとも、単にthis.options

newOptionsを割り当てることができます
this.options = newOptions; 

の作業例:https://plnkr.co/edit/lFDm7wxb56h81EAwuUNc

関連する問題