How to send sub-Components data with Vuejs 2?

Asked

Viewed 68 times

0

How can I get all the items marked from one Component in another instance by having the following tree structure?

window.Event = new Vue();

Vue.component('tree', {
	props: {
  	model: {
    	type: Array,
      default: function () { return [] }
    },
    
    checkeds: {
    	type: Array,
      default: function () { return [] }
    }
  },
  methods: {
  	changeCheck: function() {
    	Event.$emit('treeChangeCheck', this.check);
    }
  },
  data: function(){
  	return {
    	check: this.checkeds
    };
  },
	template: '\
    	<ul v-if="model.length > 0">\
      	<li><b>Checkeds:</b> {{ check }}</li>\
    		<li v-for="item in model">\
        	<input type="checkbox" @change="changeCheck" v-model="check" :value="item.id">\
          {{ item.name }}\
        	<tree :model="item.children" :checkeds="checkeds"></tree>\
        </li>\
    </ul>\
  '
});

new Vue({
	el: '#demo',
  created: function(){
  	Event.$on('treeChangeCheck', this.updateValue);
  },
  methods: {
  	updateValue: function(value){
    	this.$set(this, 'inputCheckeds', value);
    }
  },
  data: function() {
  	return {
    	inputCheckeds: [],
    	list: [
          {
            id: 1,
            name: 'Parent a',        
            children: [
                {
                    id: 2,
                    name: 'Children a.a'
                },

                {
                    id: 3,
                    name: 'Children a.b'
                }
            ]        
          },
          
          {
            id: 4,
            name: 'Parent b',        
            children: [
                {
                    id: 5,
                    name: 'Children b.a'
                },

                {
                    id: 6,
                    name: 'Children b.b'
                }
            ]        
          }
       ]
    }
  }
})
ul, li{
  margin-top: 10px;
}
p{
  margin-left: 20px
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="demo">
  <p>
  inputCheckeds: 
  {{ inputCheckeds }}
  </p>

  <tree :model="list" :checkeds="[1, 4, 2, 3]" @treeChangeInput="updateValue"></tree>
</div>

1 answer

0


I found an alternative solution using localStorage to store and control the marked/unchecked fields and this always send only the marked items to another instance.

Follows code: https://jsfiddle.net/7vp4yd46/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.