Jim Phillips
Jim Phillips

Reputation: 87

vue2.js component vmodel passing data

I'm missing a piece of understanding of how to use pass v-model data to a component.

Can I directly access the checkbox model data or do I need to pass into the component via props?

If someone code explain or point me to somewhere helpful?

My 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>

My code

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>

Upvotes: 2

Views: 672

Answers (1)

Philipp Gfeller
Philipp Gfeller

Reputation: 1269

I put together a quick codepen with your code (and mocked data): https://codepen.io/tuelsch/pen/RVrXbX?editors=1010.

To access the checkbox value test on your parent component, you can pass it as a prop to the parent component like this:

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

This way it will always be up to date on the component. In my codepen I print the values to the page to illustrate this behaviour.

If your application grows bigger you may want to consider using a flux pattern like vuex https://vuex.vuejs.org/en/ to store your filter values and access them from your components.

Upvotes: 1

Related Questions