Это старая версия документа!
Вопрос / Ответ
Вызовы компонентов
Q: Как вызвать метод из дочернего компонента?
Вызов через внешний компонент EventBus
const EventBus = new Vue(); new Vue({ name: 'app-example', created() { EventBus.$emit('firstClick'); } });
const = childComponent = { methods: { onFirstClick() { }, }, created() { EventBus.$on('firstClick', self => { this.onFirstClick(); }); }, };
<div id="app-example"> <child-component></child-component> </div
Q: Как вызвать метод из родительского компонента?
С помощью %emit
const childComponent = { name: 'child-component', methods: { something() { this.$emit('event', [x: y]); } });
<child-component @event="handler"></child-component>
new Vue({ methods: { handler(params) { console.log(params); } } });
Через ссылки $refs
import ChildForm from './components/ChildForm' new Vue({ el: '#app', data: { item: {} }, template: ` <div> <ChildForm :item="item" ref="form" /> <button type="submit" @click.prevent="submit">Post</button> </div> `, methods: { submit() { this.$refs.form.submit() } }, components: { ChildForm }, });
<template> ... </template> <script> export default { name: 'NowForm', props: ['item'], methods: { submit() { ... } } } </script>
Через системный вызов $bus
import ChildForm from './components/ChildForm' new Vue({ el: '#app', data: { item: {}, bus: new Vue(), }, template: ` <div> <ChildForm :item="item" :bus="bus" ref="form" /> <button type="submit" @click.prevent="submit">Post</button> </div> `, methods: { submit() { this.bus.$emit('submit') } }, components: { ChildForm }, });
<template> ... </template> <script> export default { name: 'NowForm', props: ['item', 'bus'], methods: { submit() { ... } }, mounted() { this.bus.$on('submit', this.submit) }, } </script>