2017-04-20 35 views
2

我很想了解如何將pass v模型數據用於組件。vue2.js組件vmodel傳遞數據

我可以直接訪問複選框模型數據,還是需要通過道具傳入組件?

如果有人的代碼解釋或指向我的某個地方有幫助嗎?

我的HTML

<template id="my-child"> 

    <tr> 
     <td >{{ item.title }}</td> 
     <td style="padding:20px" v-for="price in item.prices" v-bind:price="price" >{{ price }}</td> 
    </tr> 
    </template> 


    <template id="my-parent"> 

     <div class="box" > 
      <div v-for="item in items"> 
      <h1>{{ item.name }}</h1> 
       <img :src="item.imageUrl" style="width:200px;"> 
       <p>{{item.extract}}</p> 
       {{ item.holidayType }} 

        <div is="task" v-for="avail in item.avail" v-bind:item="avail" > 

        </div>  


      </div> 
     </div> 

    </template> 

    <div id="root"> 
     <div id="homesFilters"> 


      <input type="checkbox" id="1" value="hottub" v-model="test"> hot tub 
      <input type="checkbox" id="2" value="garden" v-model="test"> garden 
      <input type="checkbox" id="3" value="cottage" v-model="test"> cottage 
     </div> 

     <task-list></task-list> 
    </div> 

我的代碼

Vue.component('task-list', { 
    template: '#my-parent', 
    props: ['test'], 
    data: function() { 
     return { 
      items: [], 

     } 
    }, 
    methods: { 
    getMyData: function(val) { 

     console.log(this.test); 

     var _this = this; 
     $.ajax({ 
      url: 'vuejson.php', 
      method: 'GET', 
      success: function (data) { 

       _this.items = data; 
      }, 
      error: function (error) { 
       alert(JSON.stringify(error)); 
      } 
     }) 

    } 
    }, 
    mounted: function() { 
     this.getMyData("0"); 
    } 
}); 

Vue.component('task', { 

    template: '#my-child', 
    props: ['item'], 

    data: function() { 
     return { 

     } 
    } 
}); 


new Vue({ 
    el: "#root", 
    data: { 
     test:[] 
    }, 

}); 

</script> 

回答

1

我放在一起快速codepen與您的代碼(戲弄數據):https://codepen.io/tuelsch/pen/RVrXbX?editors=1010

要訪問父組件的複選框值test,你可以把它作爲一個道具到母部件是這樣的:

<task-list v-bind:test="test"></task-list> 

這樣,它永遠是最新的組件。在我的codepen中,我將值打印到頁面來說明這種行爲。

如果您的應用程序變得更大,您可能需要考慮使用像vuex https://vuex.vuejs.org/en/這樣的通量模式來存儲過濾器值並從組件訪問它們。

+0

太好了,你可以v-綁定儘可能多的瓦爾組件?我將查看vuex –

+0

'root:{{test}}'是檢查此作用域中測試內容的快捷方式,以及在檢查/取消選中過濾器時查看它如何更改。 Vue非常友善,可以用人類可讀的方式打印數組。 – phippu

+0

並且您可以將任意數量的道具傳遞給子組件:https://vuejs.org/v2/guide/components.html#Props – phippu