Pass data from child to parent in Vuejs (is it so complicated?)

后端 未结 3 446
你的背包
你的背包 2020-12-01 06:28

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

相关标签:
3条回答
  • 2020-12-01 06:51

    You aren't listening to the event. I changed the event name to clicked-show-detail. Try this.

    In the showDetailModal method of your component.

    this.$emit('clicked-show-detail', product);
    

    In your Vue.

    <list-products :products="listProducts" @clicked-show-detail="clickedShowDetailModal"></list-products>
    

    Example.

    0 讨论(0)
  • 2020-12-01 06:56

    Nightmare to find "hello world" example out there for $emit so I added the example below (Minimal lines of code + semantic names of functions).

    "Hello world" On click change parent data

    Vue.component('child', {
      template: `
    <div class="child">
    <button v-on:click="childMethod">CLICK - child Method pass data from product component</button>
    </div>
    `,
      data: function () {
        return {
          child_msg: "message from child"
        }
      },
      methods: {
        childMethod: function() {
          this.$emit('child-method', this.child_msg)
        }
      }
    })
    
    var app = new Vue({
      el: '#app',
      data: {
        msg: "I am the blue parent!!!!!!!!!!!!!!!!!!",
      },
      methods: {
        updateParent(value_from_child) {
          this.msg = value_from_child;
          alert("hello child" + value_from_child)
        }
      }
    })
    .child{ background: gray; padding: 15px; }
    button{ cursor: pointer; }
    #app{ border: 1px red dashed; padding: 15px; background: lightblue; color: blue;
    }
    <div id="app">
      <p>{{msg}}</p>
      <!-- ###### The trick happens her ###### -->
      <child class="child" v-on:child-method="updateParent"></child>
    </div> 
    
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>

    codepen: https://codepen.io/ezra_siton/pen/YzyXNox?editors=1010

    0 讨论(0)
  • 2020-12-01 06:59

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

    .

    0 讨论(0)
提交回复
热议问题