How to call a method in vue app from the vue component

后端 未结 2 2145
生来不讨喜
生来不讨喜 2021-02-20 18:58

I have a vue component and a vue element declaration as given below

Vue.component(\'todo-item\', {
  template: \'
  • This is a todo
  • \' methods:
    相关标签:
    2条回答
    • 2021-02-20 19:12

      Another solution which I think it's more accorded with Vuejs architecture, it's to use events listener & emitter between child-component and its parent to make communications.

      Check this simple fiddle as a vision

       Vue.component('todo-item', {
        template: '<li>This is a todo</li>',
        methods: {
          test: function() {
            console.log('Emmit this Event.');
            this.$emit('yourevent');
          }
        },
        created() {
          this.test();
        }
      });
      
      new Vue({
        el: '#vue-app',
        data: {
          'message': '',
        },
        methods: {
          aNewFunction(event) {
            console.log('yourevent Is Triggered!');
            this.message = 'Do Stuff...';
          },
        }
      });
      
      0 讨论(0)
    • 2021-02-20 19:13

      You can execute root instance method like this: this.$root.methodName()

        Vue.component('todo-item', {
            template: '<li>This is a todo</li>',
            methods: {
              test: function() {
                  this.$root.aNewFunction();
              }
            },
            mounted() {
              this.test();
            }
          })
      
          new Vue({
            el: '#app',
            template: '<todo-item></todo-item>',
            methods: {
              aNewFunction: function() {
                  alert("inside");
              }
            }
          })
      
      0 讨论(0)
    提交回复
    热议问题