2017-03-06 128 views
1

访问模型在VueJS我设置基于用户操作的模型数据。我想从一个方法访问模型来更新一个元素。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> 

任何想法?

+0

你无法访问'vm.options'吗?你能创造一个小提琴吗? – Saurabh

+1

@Saurabh我已经将代码更改为嵌入在html中的vue,以便将代码粘贴到HTML页面并在浏览器中打开。我不能从refreshOptions方法访问选择列表id属性或choice_id属性。 –

回答

1

在Vue公司2.X vm.$setVue.set一个别名,它需要3个参数:targetkeyvalue所以你应该使用这样的:

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

或者你可以分配给newOptionsthis.options

this.options = newOptions; 

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