美文网首页
Vue中子组件触发父组件事件的方法

Vue中子组件触发父组件事件的方法

作者: tency小七 | 来源:发表于2018-08-01 14:22 被阅读0次

1. 在子组件中进行< content @click=”close”>事件的绑定
2. 在子组件中的methods对这个close进行定义
3. methods:{
close(){
this.emit(‘on-close’) } }
也就是说,其实这个on-close是我们子组件这里的点击事件啦
4 . 在父组件中的子组件标签中绑定on-close这个事件

  1. <dialog :on-close=”beClose”></dialog>
  2. 在父组件的methods定义这个事件
    methods{
    beClose(){
    console.log(10)
    }
    }

意义:子组件中的某一个小div的点击被我们封装成'on-close'事件
父组件进行监听,一旦子组件触发了,就会调用父组件的方法

    <template>
        <button @click="emitEvent">点击我</button>
        </template>
    <script>
          export default {
          data() {
              return {
              msg: "我是子组件中的数据"
          }
          },
      methods: {
      emitEvent(){
          this.$emit('my-event', this.msg)
    //通过按钮的点击事件触发方法,然后用$emit触发一个my-event的自定义方法,传递this.msg数据。
        }
      }
    }
</script>

子组件

    <template>
      <div id="app">
      <child-a @my-event="getMyEvent"></child-a>
        <!--父组件中通过监测my-event事件执行一个方法,然后取到子组件中传递过来的值-->
      </div>
    </template>
    <script>
    import ChildA from './components/child.vue'
    export default {
        components: {
          ChildA
       },
        methods: {
        getMyEvent(msg){
            console.log('接收的数据--------->'+msg)//接收的数据--------->我是子组件中的数据
            }
        }
    }
</script>

相关文章

网友评论

      本文标题:Vue中子组件触发父组件事件的方法

      本文链接:https://www.haomeiwen.com/subject/ykmlvftx.html