父组件调用子组件方法

关键字:$refs 是一个对象,持有注册过的 ref 特性的所有DOM元素和组件实例

子组件,如下代码不用做任何特殊处理:
child.vue

  1. <template>
  2. <div>
  3. <h1>I am child</h1>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: "child",
  9. methods: {
  10. child: function () {
  11. alert("I am child");
  12. }
  13. }
  14. }
  15. </script>

父组件:
parents.vue

  1. <template>
  2. <div>
  3. <el-button @click="demo01">调用子组件方法</el-button>
  4. <child-com ref="getChild"></child-com>
  5. </div>
  6. </template>
  7. <script>
  8. import childCom from './child'
  9. export default {
  10. components: {childCom},
  11. name: "parents",
  12. methods: {
  13. demo01: function () {
  14. this.$refs.getChild.child();
  15. }
  16. }
  17. }
  18. </script>

父组件中,我们通过import 导入子组件后,如果想用子组件提供的方法,我们需要再子组件中 加入 ref=’xxx’ xxx仅仅是个占位符名称随意。 然后编写方法调用子组件方法。 直接通过this.$refs.占位符.子组件方法名() 调用。

子组件调用父组件方法

关键字:$emit 触发当前实例上的事件。附加参数都会传给监听器回调。

我们先看父组件。编写了自己的parents() 方法外,引用了子组件。 为了能让 parents()方法能被child子组件待用,需要在Dom节点上添加 @xxx=”parents()”。 其中xxx为子组件调用时使用的名称。 parents()就是父组件的方法。
parents.vue

  1. <template>
  2. <div>
  3. <child-com @par="parents"></child-com>
  4. </div>
  5. </template>
  6. <script>
  7. import childCom from './child'
  8. export default {
  9. components: {childCom},
  10. name: "parents",
  11. methods: {
  12. parents: function (parameter) {
  13. alert(`I am ${parameter}`);
  14. }
  15. }
  16. }
  17. </script>
  18. <style scoped>
  19. </style>

子组件代码如下,需要添加调用父组件方法,并在该方法下通过this.$emit(‘xxx’, ‘parameter’)调用父组件方法。 其中xxx为父组件给子组件提供的占位符,parameter为父组件方法的参数。
child.vue

  1. <template>
  2. <div>
  3. <el-button @click="childM">调用父组件方法</el-button>
  4. <h1>I am child</h1>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: "child",
  10. methods: {
  11. childM:function () {
  12. this.$emit('par', 'meyoung')
  13. }
  14. }
  15. }
  16. </script>

子组件使用父组件属性

  1. 在父组件中导入子组件,并添加 自定义名称,如下::searchData为自定义名称,searchData为父组件的data中的属性searchData:{}

    1. <net-work :searchData="searchData"/>
  2. 子组件添加props,例如下,searchData为第一步的自定义名称,type为父组件searchData:{}的类型,default为默认值,可以省略

    1. props: {
    2. searchData: {
    3. type: Object,
    4. default: {}
    5. }
    6. },
  3. 子组件使用,如下:

    1. let serverName = this.searchData.servername;
    2. let startTime = this.searchData.startTime;
    3. let endTime = this.searchData.endTime;