首页 > 其他 > 详细

【转】vue 子页面调用父页面常用方式

时间:2020-02-21 11:53:43      阅读:43      评论:0      收藏:0      [点我收藏+]

方式一

$parent
父组件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from ‘./child‘;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod(str) {
        console.log(str);
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod(‘hello‘);
      }
    }
  };
</script>

方式二

props
父组件

<template>
  <div>
    <child :fatherMethod="fatherMethodOther"></child>
  </div>
</template>
<script>
  import child from ‘./child‘;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethodOther(str) {
        console.log(str);
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod">点击</button>
  </div>
</template>
<script>
  export default {
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod(‘hello‘);
        }
      }
    }
  };
</script>

方式三

$emit
父组件

<template>
  <div>
    <child @fatherMethod="fatherMethodOther"></child>
  </div>
</template>
<script>
  import child from ‘./child‘;
  export default {
    components: {
      child
    },
    methods: {
      fatherMethodOther(str) {
        console.log(str);
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$emit(‘fatherMethod‘, ‘hello‘);
      }
    }
  };
</script>

第一种不推荐,一般第三种。



作者:lesdom
链接:https://www.jianshu.com/p/3b2651529dad
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

【转】vue 子页面调用父页面常用方式

原文:https://www.cnblogs.com/myobject/p/12340594.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!