javascript - 如何在Vue组件中导入外部函数?

标签 javascript vue.js

我是 javascript 和 vue.js 的新手,在尝试在现有程序中添加新功能时遇到了一些问题。

我已将我的新函数(与其他函数)放在一个单独的文件中:

export const MyFunctions = {
MyFunction: function(param) {
    // Doing stuff
}
}

然后我将文件导入组件文件并调用我的函数:

<script>
    import {MyFunctions} from "@/components/MyFunctions.js";
    export default {
        name:"Miniature",
        computed: {
            useMyFunction() {
                MyFunction("Please do some stuff !");
            }
        }
    }
</script>

当组件被使用时,我得到一个错误信息

[Vue warn]: Property or method "MyFunction" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

我阅读了很多文档,但不明白为什么它不起作用。谁能帮我解决这个问题??

最佳答案

您正在导出一个对象,然后为了使用 MyFunction,您需要使用点符号访问该函数,如下所示:MyFunctions.MyFunction("请做一些事情! ")

我为这个用例做了一个工作示例:https://codesandbox.io/s/62l1j19rvw


MyFunctions.js

export const MyFunctions = {
  MyFunction: function(param) {
    alert(param);
  }
};

组件

<template>
  <div class="hello">
   {{msg}}
   <button @click="handleClick">Click me</button>
  </div>
</template>

<script>
import {MyFunctions} from "../MyFunctions.js";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  methods:{
    handleClick: function(){
      MyFunctions.MyFunction("Please do some stuff !");
    }
  }
};
</script>

关于javascript - 如何在Vue组件中导入外部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777182/

相关文章:

javascript - 环境声明样式和模块

javascript - 如何将本地文本文件上传到文本区域(网页内)

javascript网格按数字排序,排序问题

javascript - console.log、Object.keys 和 Object.getOwnPropertyNames 之间的不一致

vue.js - 错误 : You cannot call "get" on a collection with no paths. 相反,首先检查 "length"属性以验证至少存在 1 个路径

javascript - VanillaJS 到 VueJS 错误 : bad element for Flickity: carousel

javascript - 如何从另一个方法获取变量的值? (vue.js 2)

javascript - 将整数值更改为字符串或插入掩码

vue.js - 如何将 vuestorefront 与 shopify 集成

javascript - icheck-box 组件中的 v-model 在 vue 中不起作用