码迷,mamicode.com
首页 > 其他好文 > 详细

vue中子组件触发父组件的方法

时间:2019-01-16 13:10:37      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:this   ack   return   OLE   editor   exp   def   temp   sub   

网上找了几种方法,下面这两种最实用,最明了

方法一:父组件方法返回是字符串或数组时用这种方法

子组件:

<template>
    <button @click="submit">提交</button>
</template>
<script>
export default {
  methods: {
    submit: function () {
      // 子组件中触发父组件方法ee并传值1
       this.$emit(‘ee‘, ‘1‘)
    }
  }
}
</script>

  

父组件:

<template>
    <editor id="editor" class="editor" @ee="cc"></editor>
</template>
<script>
export default {
  data() {
    return {
      text: ‘‘
    }
  },
  methods: {
    cc: function (str) {
      if(str === 1){
        this.text = ‘中国‘
      } else {
        this.text=‘美国‘ 
      }
    }
  }
}
</script>

方法二:父组件方法返回是boolean类型时用这种方法

子组件:

<template>
    <button @click="submit">提交</button>
</template>
<script>
export default {
  props: {
    validate: {
      type: Function,
      default: null
    }
  },
  methods: {
    submit: function () {
// 子组件触发父组件方法goValidate并传值data let data
= { newName:"张三", oldName:"李四" } if (!that.validate(data)) { console.log(新名:+data.newName) } } } } </script>

 

父组件:

<template>
    <editor id="editor" class="editor" :validate="goValidate"></editor>
</template>
<script>
export default {
  methods: {
    goValidate: function (data) {
      let newName = data.newName
      if (newName.length < 1) {
         layer.msg(‘命名不能为空,请重新输入!‘, { icon: 7 })
         return false
     }
     return true
    }
  }
}
</script>

  

 

 

  

vue中子组件触发父组件的方法

标签:this   ack   return   OLE   editor   exp   def   temp   sub   

原文地址:https://www.cnblogs.com/fifteen-wu/p/10276293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!