在'export default'之外的组件内调用VueJS方法

问题描述 投票:4回答:4

我试图从外面调用'method'中的函数。但是,它不起作用。

Github问题报道相同:https://github.com/vuejs/vue/issues/329

vm.test(); // call a function in method, not working
this.vue.test()  // not working
export default {
  methods: {
    test: function() {
      alert('test fuction called');
    }
  }
}
vue.js vuejs2 vue-component
4个回答
5
投票

目前尚不清楚原始海报的实际目标是什么,但是在创建它之后,您可以在Vue实例上调用方法:

var viewModel = new Vue({
    el: "#app",
  data: {
    msg: "Hello there"
  },
  methods: {
    test: function() {
      alert('test fuction called');
    }
  }
});

viewModel.test();

工作示例:https://jsfiddle.net/Daryn/Lja7pake/3/

如果要导出单个文件组件,请尝试以下操作:

example.js

<script>
   export default {
    methods: {
      test: function() {
      alert('test fuction called');
     }
    }
   }
</script>

main.js

<script>
    import Thing from './example.js';
    Thing.test();
</script>

参考:https://vuejs.org/v2/guide/single-file-components.html


3
投票

你想要实现的是根本上有缺陷的。除非您具有对该特定组件的实例的引用,否则无法调用组件的方法。在你的代码中,vm指的是哪个特定组件?

您所做的只是从模块中导出Vue组件定义;这里没有实例化组件。

我们需要查看更多代码或完整解释您正在尝试实现的目标,以便我们提供替代解决方案。 (为什么要尝试在其定义之外调用组件的方法?)


0
投票
export default {
  ...
  methods: {
    ...
  },
  mounted () {
    EventBus.$on(‘EVENT_NAME’, function (payLoad) {
      ...
    });
  }
}

0
投票

这就是我解决这个问题的方法。

出于演示的目的,我们使用Vue / CLI创建一个新项目。安装完成后,我们将vm暴露给全局。打开src/main.js并编辑如下:

SRC / main.js

import Vue from 'vue';
import App from './App.vue';

var vm = new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

// Add this line (tambahkan baris berikut):
window.vm = vm;

保留生成的App.vue就像它一样。所以vm(vm.$children[0])的第一个孩子是App.vue

我们看到App.vue有一个孩子。这使得HelloWorld.vue成为vm(vm.$children[0].$children[0])的大孩子。知道了这一点,我们可以从外部'export default'调用这样的方法:

SRC /组件/ HelloWorld.vue

<template>
  <div class="hello">
    <button 
      id="sebuahButton" 
      class="btn btn-outline-secondary btn-sm" 
      type="button"
    >Click Me, Jose!</button>
    <h1>{{ msg }}</h1>
    <!-- and some stuff, vue cli default generated code -->
  <div>
</template>

<script>
(function() {
    // wait for the DOM ready event in plain JavaScript
    document.addEventListener("DOMContentLoaded", event => {
        document.getElementById("sebuahButton").onclick = function() {
            vm.$children[0].$children[0].someAction();
        };
    });
})();

export default {
    name: "HelloWorld",
    props: {
        msg: String
    }
    methods: {
        someAction () {
            // do something (lakukan sesuatu masbro!)
            console.log("It's been called from outer space, Luke!");
        }
    }
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.