程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Vue中子组件调用父组件的三种方法

发布于2022-05-31 21:40     阅读(510)     评论(0)     点赞(13)     收藏(1)


Vue中子组件调用父组件的三种方法:

1.直接在子组件中通过“this.$parent.event”来调用父组件的方法。

父组件

  1. <template>
  2. <div>
  3. <child></child>
  4. </div>
  5. </template>
  6. <script>
  7. import child from './components/childcomponent';
  8. export default {
  9. components: {
  10. child
  11. },
  12. methods: {
  13. fatherMethod() {
  14. console.log('父组件方法');
  15. }
  16. }
  17. };
  18. </script>

子组件

  1. <template>
  2. <div>
  3. <button @click="childMethod()">点击按钮</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. methods: {
  9. childMethod() {
  10. this.$parent.fatherMethod();
  11. }
  12. }
  13. };
  14. </script>

2.子组件用“$emit”向父组件触发一个事件,父组件监听这个事件即可。

父组件

  1. <template>
  2. <div>
  3. <child @fatherMethod="fatherMethod"></child>
  4. </div>
  5. </template>
  6. <script>
  7. import child from './components/childcomponent'
  8. export default {
  9. components: {
  10. child
  11. },
  12. methods: {
  13. fatherMethod() {
  14. console.log('父组件方法');
  15. }
  16. }
  17. };
  18. </script>

子组件

  1. <template>
  2. <div>
  3. <button @click="childMethod()">点击按钮</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. methods: {
  9. childMethod() {
  10. this.$emit('fatherMethod');
  11. }
  12. }
  13. };
  14. </script>

3.父组件把方法传入子组件中,在子组件里直接调用这个方法即可。

父组件

  1. <template>
  2. <div>
  3. <child :fatherMethod="fatherMethod"></child>
  4. </div>
  5. </template>
  6. <script>
  7. import child from './components/childcomponent';
  8. export default {
  9. components: {
  10. child
  11. },
  12. methods: {
  13. fatherMethod() {
  14. console.log('父组件方法');
  15. }
  16. }
  17. };
  18. </script>

子组件

  1. <template>
  2. <div>
  3. <button @click="childMethod()">点击按钮</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. props: {
  9. fatherMethod: {
  10. type: Function,
  11. default: null
  12. }
  13. },
  14. methods: {
  15. childMethod() {
  16. this.fatherMethod();
  17. }
  18. }
  19. }
  20. };
  21. </script>

原文链接:https://blog.csdn.net/qq_44858608/article/details/124156157




所属网站分类: 技术文章 > 博客

作者:大哥你来啦

链接:http://www.qianduanheidong.com/blog/article/361042/482c405ec73cc4eafffc/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)