Vue在子组件中调用父组件的方法并传参

1.在父组件 methods 中定义 show 方法,供子组件调用。

    methods:{
      show(data){
        this.datamsgFormSon = data
		console.log(this.datamsgFormSon)
      }
    },

2. 在引用子组件的时候,将 父组件的 show 方法传递给子组件。

使用的是事件绑定机制,v-on。

<com2 v-on:func="show"></com2>

 3. 定义子组件com2

在子组件的data中定义 sonmsg 属性,定义 myclick 方法来调用父组件的方法。在调用的时候使用 $emit

var com2 = {
    template:'#tmp1',
    data(){
      return{
        sonmsg:{name:'小头儿子',age:6}
      }
    },
    methods:{
      myclick(){
        //当点击子组件的按钮的时候,如何拿到父组件传递过来的func方法,并调用这个方法
        //英文愿意:是触发,调用、发射的意思
        this.$emit('func',this.sonmsg)
      }
    }
  }

完整代码:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
<body>
  <div id='app'>
    <!-- 父组件向子组件传递方法,使用的是事件绑定机制,v-on,
    当我们自定义了一个事件属性之后,子组件就能够通过某些方式,来调用传递进去的这个方法了 -->
   <com2 v-on:func="show"></com2>
  </div>
  <template id="tmp1">
    <div>
      <h1>这是子组件</h1>
        <input type="button" value="这是子组件中的按钮,-点击它,触发父组件传递过来的func方法" @click="myclick">
    </div>
  </template>
</body>
<script src="../lib/vue.js"></script>
<script>
  var com2 = {
    template:'#tmp1',
    data(){
      return{
        sonmsg:{name:'小头儿子',age:6}
      }
    },
    methods:{
      myclick(){
        //当点击子组件的按钮的时候,如何拿到父组件传递过来的func方法,并调用这个方法
        //英文愿意:是触发,调用、发射的意思
        this.$emit('func',this.sonmsg)
      }
    }
  }
  var vm = new Vue({
    el:'#app',
    data:{
      datamsgFormSon:null
    },
    methods:{
      show(data){
        this.datamsgFormSon = data
		console.log(this.datamsgFormSon);
      }
    },
    components:{
      com2,
    }
  })
</script>
</html>
发布了95 篇原创文章 · 获赞 216 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/82458881