十八力丁

导航

【vue】组件沟通

组件调用

原文出处:https://www.cnblogs.com/ming-os9/p/9004071.html  cnblogs博主「ming-os9

<template>  
    <div>  
        <!-- 3.在template中就可以直接使用了 -->  
        <testComponent></testComponent>  
    </div>  
</template>  

<script>  
   
    //1.先使用import导入你要在该组件中使用的子组件  
    import testComponent from './testComponent.vue'  
    export default {  
        //2.然后,在components中写入子组件  
        components: {testComponent},  
        methods: {},  
    } 
  /* 方法二:直接在component中写入子组件
    export default {
      components: {
        testComponent:require('./testComponent.vue').default
       }
       methods: {},
    } */
</script>  
  
<style></style>

组件函数互相调用

原文(组件函数互相调用1-3)出处:https://www.cnblogs.com/jin-zhe/p/9523782.html  cnblogs博主「靳哲」

一、父组件调用子组件函数

父组件:

<template>
    <child ref="childFunc"></child>
</template>

父组件调用子组件方法

this.$refs.childFunc.func(params)

二、子组件调用父组件

方法1:使用$parent

this.$parent.fatherMethod();

方法2:使用$emit向父组件触发事件,父组件监听这个事件

父组件

<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件

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

方法3:父组件把方法传给子组件,在子组件里直接调用

父组件

<template>
  <div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</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();
        }
      }
    }
  };
</script>

方法4:vue依赖注入provide - inject 实现子组件调用父组件的方法

原文出处:https://www.cnblogs.com/peatechen/p/11096631.html  cnblogs博主「SmallPeate」

父组件提供provide,允许指定方法提供给后代组件的数据

provide: function () {
    return {
       getMap: this.getMap
    }
}

子组件使用inject接受实例上的属性

inject: ['getMap']

缺陷

然而,依赖注入还是有负面影响的。它将你应用程序中的组件与它们当前的组织方式耦合起来,使重构变得更加困难。同时所提供的属性是非响应式的。
这是出于设计的考虑,因为使用它们来创建一个中心化规模化的数据跟使用 $root做这件事都是不够好的。
如果你想要共享的这个属性是你的应用特有的,而不是通用化的,或者如果你想在祖先组件中更新所提供的数据,那么这意味着你可能需要换用一个像 Vuex 这样真正的状态管理方案了。

 

 

 

posted on 2019-11-26 11:52  十八力丁  阅读(31)  评论(0)    收藏  举报