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

新手上路,请多包涵

我是 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 警告]:属性或方法“MyFunction”未在实例上定义,但在渲染期间被引用。通过初始化属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。请参阅: https ://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。

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

原文由 MrFernand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 854
2 个回答

您正在导出一个对象,然后为了使用 MyFunction 您需要使用点表示法访问该函数,如下所示: MyFunctions.MyFunction("Please do some stuff !")

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


我的函数.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>

原文由 You Nguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议

您只需将 javascript 文件导入 .vue 文件,只要它们在 <script> 标签内即可。因为 Vue.js 毕竟 是 javascript,所以在调试时你应该看的第一部分是你的语法是否有某种错误。据我所知, importexport 语句有些混淆,起初可能非常复杂!

专门在 named exports 下查看 MDN 的文档

在模块中,我们可以使用以下内容

// module "my-module.js"
function cube(x) {
  return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = { /* nice big object */ }
export { cube, foo, graph };

这样,在另一个脚本中,我们可以:

 import { cube, foo, graph } from 'my-module';
// Use your functions wisely

原文由 nicoramirezdev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题