Это старая версия документа!
Вопрос / Ответ
Вызовы компонентов
Q: Как вызвать метод из дочернего компонента?
Vue( );
const = childComponent = { data: function () { return { childData: '' } }, props: { parentData: { type: String, default () { return '' } } }, methods: { // maybe onchagne may onclick whatever.. handleDataFc: function () { this.$emit('interface', this.childData) // handle data and give it back to parent by interface } }, beforeMount () { this.childData = this.parentData // save props data to itself's data and deal with it } };
<div id="counter-event-example"> <child-component :parentData="parentData" @interface="handleFcAfterDateBack"> </child-component> <child-component :parentData="parentData" @interface="parentData = $event"> </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>