[英]How to import a external function in a Vue component?
我是 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。
我已經閱讀了很多文檔並且無法理解為什么它不起作用。 誰能幫我這個 ??
您正在導出一個對象,然后為了使用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>
您可以將您的 javascript 文件導入到.vue
文件中,只要它們位於<script>
標簽內即可。 由於Vue.js 畢竟是 javascript,因此在調試時應該查看的第一部分是語法是否存在某種錯誤。 據我所知, import
和export
語句有些混亂,一開始可能很復雜!
在模塊中,我們可以使用以下內容
// 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
您導出的是一個對象,而您使用的是該對象內部的一個字段/方法,因此您需要以這種方式使用您的函數:
MyFunctions.MyFunction("Please do some stuff !");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.