[Vuejs]-Vue 2 – get clossest element with a class

4👍

What you are describing is a very non Vue way to go about things. What I would do is define a component. I realize that this doesn’t work completely with your code as it is, but bear with me.

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>

Your template would then become something like this

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

The individual countries are passed into the component as properties. Inside the component, the code uses v-model to bind the data to the internal country data so they are automatically updated. Then, when you need to do something in updateCountry you already have the values.

👤Bert

Leave a comment