Это старая версия документа!


Вопрос / Ответ

Вызовы компонентов

Вызов чере $props

 

Вызов через глобальный компонент 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', parent => {
            this.onFirstClick();
        });
    },
};
<div id="app-example">
 <child-component></child-component>
</div

С помощью %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>
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>