【问题标题】:How to import a external function in a Vue component?如何在 Vue 组件中导入外部函数?
【发布时间】:2019-03-17 13:07:16
【问题描述】:

我是 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://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties

我已阅读大量文档,但无法理解为什么它不起作用。谁能帮我这个 ??

【问题讨论】:

  • 您正在导入 MyFunctions,但您的错误消息显示为 changeFavicon

标签: javascript vue.js


【解决方案1】:

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

我为这个用例做了一个工作示例: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>

【讨论】:

  • 刚刚偶然发现了这个答案,虽然它有效,但我确实遇到了一些错误,我不知道该怎么办 - 属性或方法“handleClick”未在实例上定义,但在渲染期间被引用。和 - 事件“点击”的无效处理程序:未定义
【解决方案2】:

您可以将您的 javascript 文件导入到 .vue 文件中,只要它们位于 &lt;script&gt; 标记内即可。由于 Vue.js 毕竟是 javascript,所以在调试时您应该查看的第一部分是您的语法是否存在某种错误。据我所知,importexport 语句存在一些混淆,一开始可能相当复杂!

特别在named exports下查看MDN's Documentation

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

// 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

【讨论】:

    【解决方案3】:

    你导出的是一个对象,你使用的是这个对象内部的一个字段/方法,所以你需要这样使用你的函数:

    MyFunctions.MyFunction("Please do some stuff !");
    

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2017-05-08
      • 2021-01-13
      • 1970-01-01
      • 2018-08-15
      • 2017-05-18
      相关资源
      最近更新 更多