2017-06-18 188 views
0

我有我的模板如下:Vue公司2 - 讓clossest元素與類

<tbody> 

    @foreach ($countries as $country) 
     <tr class="parent"> 
      <td><input class="form-control" type="text" value="{{ $country->name }}"></td> 
      <td>{{ $country->show ? 'Yes' : 'No' }}</td> 
      <td><input class="form-control" type="number" value="{{ $country->order }}"></td> 

      <td> 
       <button class="btn btn-primary">{{ $country->show ? "Hide" : "Show" }}</button> 
       <button class="btn btn-success" @click="updateCountry">Update</button> 
      </td> 
     </tr> 
    @endforeach 

</tbody> 

這是Vue公司代碼:

import Vue from 'vue' 

let App = new Vue({ 

    el: '#app-container', 

    data: { 

    }, 

    methods: { 
     filterCountries() { 

     }, 

     updateCountry(event) { 
      console.log(event.target.parentElement); 
     } 
    } 

}) 

到目前爲止,我可以得到一個參考父母(這是包含按鈕的td)。是否有可能得到類(類似於jquery)最接近的元素,然後獲取包含在父元素中的輸入元素的值?

回答

3

你所描述的是一種非常非Vue的方式去做的事情。我會做的是定義一個組件。我意識到,這並不完全適用於你的代碼,因爲它是,但忍受着我。然後

console.clear() 
 

 
Vue.component("country",{ 
 
    props:["country"], 
 
    template: "#country-template", 
 
    data(){ 
 
    return { 
 
     internalCountry: this.country 
 
    } 
 
    }, 
 
    methods:{ 
 
    updateCountry(){ 
 
     console.log(this.internalCountry) 
 
    } 
 
    } 
 
}) 
 

 
let App = new Vue({ 
 

 
    el: '#app-container', 
 

 
    data: { 
 
     country:{ 
 
     name:"Germany", 
 
     order: 1, 
 
     show: true 
 
     } 
 
    }, 
 

 
    methods: { 
 
     filterCountries() { 
 

 
     }, 
 

 
     updateCountry(event) { 
 
      console.log(event.target.parentElement); 
 
     } 
 
    } 
 

 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 

 
<div id="app-container"> 
 
    <table> 
 
    <tbody> 
 
     <tr is="country" :country="country"></tr> 
 
    </tbody> 
 
    </table> 
 
</div> 
 

 

 
<template id="country-template"> 
 
    <tr class="parent"> 
 
    <td><input class="form-control" type="text" v-model="internalCountry.name"></td> 
 
    <td>{{ internalCountry.show ? 'Yes' : 'No' }}</td> 
 
    <td><input class="form-control" type="number" v-model="internalCountry.order"></td> 
 

 
    <td> 
 
     <button class="btn btn-primary">{{ internalCountry.show ? "Hide" : "Show" }}</button> 
 
     <button class="btn btn-success" @click="updateCountry">Update</button> 
 
    </td> 
 
    </tr> 
 
</template>

你的模板將成爲這樣的事情

@foreach ($countries as $country) 
    <tr is="country" :country="{{$country}}"></tr> 
@endforeach 

個別國家傳遞到組件的屬性。在組件內部,代碼使用v-model將數據綁定到內部國家/地區數據,因此它們自動已更新。那麼,當你需要在updateCountry中做點什麼時,你的已經有了的值。

+0

感謝您的資源豐富的答案:)。我剛開始學習Vue,並且我正在一步一步:) – Sasha