M
M
Mr_Romanov2019-04-13 13:58:43
Vue.js
Mr_Romanov, 2019-04-13 13:58:43

REF in VUEJS how to call a method from another component?

I'm trying to figure out how to call methods from different components, I figured it out from child ones

this.$root.$on('Мойкомпонент',() => {
                this.Мойметод();
           
            })

///и в дочернем компоненте
this.$root.$emit('Мойкомпонент')

I hope right?
And how can I call a method that is not associated with a component in any way?
Googled ref, trying
<tenant-number-modal ref="modal"></tenant-number-modal>

      methods: {
         openModal() {
            this.$refs.modal.showModal();
         }
      }


//Источник метода

    methods: {
       showModal() {
       this.dialog = true;
       }
    }

VUE swears at tenant-number-modal and of course the method does not work, am I doing something wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
ned4ded, 2019-04-13
@Mr_Romanov

Good afternoon!
According to the official style guide , you should avoid using any state management other than through vuex.
In order, then I know two patterns that will solve the problem of communication of the view components: the flux design pattern (implemented using the vuex library ), and the event bus.
What you are trying to do is an event bus, only instead of using a separate view instance, you are using the root instance as the bus (at least in the first part of the code).
If there is no desire to understand vuex, then try to organize work through the bus, it is suitable for both of the cases you listed.
The event bus for the view is based on custom events built into the view (implemented through vm.$on and vm.$emit, more details ). Usually another instance of the view is created:

// Дальше идет псевдокод, возможны синтаксические ошибки.

// event-bus.js
import Vue from 'vue'

export default new Vue()

// app.js
import Vue from 'vue'
import bus from './event-bus'

export default new Vue({
  created() {
     bus.$on('some-event', () => { console.log('hi!') })
  },

  components: {
    child: {
      methods: {
        triggerSomeEvent() {
          bus.$emit('some-event')
        }
      }
    }
  }
})

You import this bus into those components that are tied to events initialized in this bus (that is, both the sender and receiver of the event), it will not matter here whether it is a parent, child, child or independent component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question