Vue父组件中调用子组件的方法
方法一:通过ref直接调用子组件的方法
//父组件中
<template>
<div>
<Button @click="search">点击/Button>
<Childrenref="children"/>
</div>
</template>
<script>
import Child from '../model/children';
export default {
methods: {
search() {
this.$refs.children.loading();
},
},
}
</script>
//子组件中
<template>
<div>我是子组件</div>
</template>
<script>
export default {
methods: {
loading () {
console.log('1111111');
},
},
};
</script>
方案二:通过组件的 $emit、 $on方法;
//父组件中
<template>
<div>
<Button @click="search">点击/Button>
<Childrenref="children"/>
</div>
</template>
<script>
import Child from '../model/children';
export default {
methods: {
search() {
this.$refs.child.$emit("loading") //子组件$on中的名字
},
},
}
//子组件中
<template>
<div>子组件</div>
</template>
<script>
export default {
mounted() {
this.$nextTick(function() {
this.$on('loading', function() {
console.log('111111111');
});
});
},
};
</script>