1.通过ref直接调用子组件的方法;

2.通过组件的$emit、$on方法;

方案一:通过ref直接调用子组件的方法;

访问子组件实例或子元素

尽管存在 prop 和事件,有的时候你仍可能需要在 JavaScript 里直接访问一个子组件。为了达到这个目的,你可以通过 ref 这个 attribute 为子组件赋予一个 ID 引用。例如:

<base-input ref="usernameInput"></base-input>

现在在你已经定义了这个 ref 的组件里,你可以使用:

this.$refs.usernameInput

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

//父组件中

<template>

    <div>

        <Button @click="handleClick">点击调用子组件方法</Button>

        <Child ref="child"/>

    </div>

</template>   

<script>

import Child from './child';

export default {

    methods: {

        handleClick() {

              this.$refs.child.sing();

        },

    },

}

</script>

//子组件中

<template>

  <div>我是子组件</div>

</template>

<script>

export default {

  methods: {

    sing() {

      console.log('我是子组件的方法');

    },

  },

};

</script>

方案二:通过组件的$emit、$on方法;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

//父组件中

<template>

    <div>

        <Button @click="handleClick">点击调用子组件方法</Button>

        <Child ref="child"/>

    </div>

</template>   

<script>

import Child from './child';

export default {

    methods: {

        handleClick() {

               this.$refs.child.$emit("childmethod")    //子组件$on中的名字

        },

    },

}

</script>

//子组件中

<template>

    <div>我是子组件</div>

</template>

<script>

export default {

    mounted() {

        this.$nextTick(function() {

            this.$on('childmethods', function() {

                console.log('我是子组件方法');

            });

        });

     },

};

</script>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐