1、使用this.$parent.event直接调用
//父组件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
father() {
console.log('提交');
}
}
};
</script>
//子组件
<template>
<div>
<button @click="submit()">点击</button>
</div>
</template>
<script>
export default {
methods: {
submit() {
this.$parent.father();
}
}
};
</script>
2、通过$emit触发一个事件,父组件监听
//父组件
<template>
<div>
<child @father="father"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
father() {
console.log('提交');
}
}
};
</script>
//子组件
<template>
<div>
<button @click="submit()">点击</button>
</div>
</template>
<script>
export default {
methods: {
submit() {
this.$emit('father');
}
}
};
</script>
3、使用props
//父组件
<template>
<div>
<child :father="father"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
father() {
console.log('提交');
}
}
};
</script>
//子组件
<template>
<div>
<button @click="submit()">点击</button>
</div>
</template>
<script>
export default {
props: {
father: {
type: Function,
default: null
}
},
methods: {
submit() {
this.father()
}
}
};
</script>
三种区别: 三种都可以实现子组件调用父组件的方法,但是效率有所不同
this.$parent.event可以调用父组件身上的方法,无需绑定在子组件身上。缺点:有时候会失效,暂未发现触发点,不建议使用。
$emit可以调用父组件在子组件身上自定义的事件,需要用@前缀。建议使用此种方式
props可以调用父组件绑定在子组件身上的事件,需要:前缀。在router-view身上使用失效