Это старая версия документа!
Вопрос / Ответ
Вызовы компонентов
Q: Как вызвать метод из дочернего компонента?
Вызов чере $props
ребенок
const Mouse = { name: "Mouse", props: { render: { type: Function, required: true } }, data() { return { x: 0, y: 0 }; }, methods: { handleMouseMove(event) { this.x = event.clientX; this.y = event.clientY; } }, render(h) { return ( <div style={{ height: "100%" }} onMousemove={this.handleMouseMove}> {this.$props.render(this)} </div> ); } };
родитель
new Vue({ el: '#app', name 'app', components: { Mouse }, methods: { __render({ x, y }) { return ( <h1> The mouse position is ({x}, {y}) </h1> ); } }, created() { } });
<div id="app"> <Mouse :render="__render"/> </div>
Вызов через глобальный компонент EventBus
const EventBus = new Vue(); new Vue({ name: 'app-example', created() { EventBus.$emit('firstClick'); } });
const = childComponent = { methods: { onFirstClick() { }, }, created() { EventBus.$on('firstClick', parent => { this.onFirstClick(); }); }, };
<div id="app-example"> <child-component></child-component> </div
Если не нужны параметры, можно parent заменить на ()
EventBus.$on('firstClick', () => { this.onFirstClick(); });
Вызов через зарегистрированный компонент EventBus
var bus = new Vue({}); Object.defineProperty(Vue.prototype, '$bus', { get(){ return this.$root.bus; }, set(newInstance){ this.$root.bus = newInstance; }, }); new Vue({ name: 'app-example', created() { this.$bus.$emit('firstClick'); } });
const = childComponent = { methods: { onFirstClick() { }, }, created() { this.$bus.$on('firstClick', (event) => { 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>