Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vue.js - Pass data from child to parent in Vuejs (is it so complicated?)

Thanks for reading my question.

I have read about it:

vuejs update parent data from child component

https://forum.vuejs.org/t/passing-data-back-to-parent/1201/2

The concept is the same, I need to pass a data object from child to parent. I have used $emit to pass data to parent component but it doesn't works. Do you know what is wrong? You can check my code here:

Vue.component('list-products', {
  delimiters: ['[[', ']]'],
  template: '#list-products-template',
  props: ['products'],
  data: function () {
    return {
      productSelected: {}
    }
  },
  methods: {
    showDetailModal: function (product) {
    console.log('click product in child, how can i pass this product to productSelected data in parent?');
      console.log(product);
      this.productSelected = product;
      this.$emit('clickedShowDetailModal', product);
    }
  }
});


var app = new Vue({
  delimiters: ['[[', ']]'],
  el: '#resultComponent',
  data: {
    listProducts: [
      {'name':'test1',id:1},
        {'name':'test2',id:2},
        {'name':'test3',id:3}
    ],
    productSelected: {}
  },
  methods: {
    clickedShowDetailModal: function (value) {
      console.log('value');
      console.log(value);
      this.productSelected = value;
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="resultComponent" data-toggler=".small-up-2" class="row small-up-1">
  <list-products :products="listProducts"></list-products>
</div>

<script type="text/x-template" id="list-products-template">
  <div>
    <div class="column column-block" v-for="(product, index) in products" :product="product" :index="index" :key="product.id">
    <li class="more-benefits">
        <a @click="showDetailModal(product)">Click me [[ product.name ]] and check console.log ?</a>
    </li>
    </div>
  </div>
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Props are for parent -> child

You can use $emit for child -> parent

v-on directive captures the child components events that is emitted by $emit

Child component triggers clicked event :

export default {
   methods: {
     onClickButton (event) {
         this.$emit('clicked', 'someValue')
     }
   }
}

Parent component receive clicked event:

<div>
    <child @clicked="onClickChild"></child>
</div>

...

export default {
  methods: {
      onClickChild (value) {
          console.log(value) // someValue
      }
  }
}

.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...