vue

vue父组件中调用子组件的方法

ref|组件的$emit、$on方法

Posted by Sunfy on 2021-08-18
Words 321 and Reading Time 1 Minutes
Viewed Times
Viewed Times
Visitors In Total

vue解决跨域问题

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

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>

Copyright 2021 sunfy.top ALL Rights Reserved

...

...

00:00
00:00