admin管理员组文章数量:1356808
Let's say that in a VueJS project, I have a HelloWorld.js file like this:
export default {
addNumbers: function (a,b) {
return a+b;
}
}
And it's used from HelloWorld.vue like this:
<template>
<div>
<h1>{{addNumbers(1,2)}}</h1>
</div>
</template>
<script>
import helloWorldJS from './HelloWorld.js'
export default {
name: 'HelloWorld',
methods: {
addNumbers: function(a,b) {
return helloWorldJS.addNumbers(a,b);
}
}
}
</script>
My agony es from having to 'duplicate' the addNumbers function in the methods section of the HelloWorld ponent.
Is there a simple way to make the external addNumbers function available from the template section?
Let's say that in a VueJS project, I have a HelloWorld.js file like this:
export default {
addNumbers: function (a,b) {
return a+b;
}
}
And it's used from HelloWorld.vue like this:
<template>
<div>
<h1>{{addNumbers(1,2)}}</h1>
</div>
</template>
<script>
import helloWorldJS from './HelloWorld.js'
export default {
name: 'HelloWorld',
methods: {
addNumbers: function(a,b) {
return helloWorldJS.addNumbers(a,b);
}
}
}
</script>
My agony es from having to 'duplicate' the addNumbers function in the methods section of the HelloWorld ponent.
Is there a simple way to make the external addNumbers function available from the template section?
Share Improve this question asked Dec 19, 2020 at 7:44 ThomasEThomasE 4312 gold badges7 silver badges21 bronze badges2 Answers
Reset to default 7you could export as const you function like:
export const addNumbers = (a,b) => a+b;
then at your vue file you could write as:
import { addNumbers } from './HelloWorld.js'
export default {
name: 'HelloWorld',
methods: {
addNumbers // this is equal to addNumbers: addNumbers
}
}
You can't directly import the method and use it on the template in vue. You can only use functions that are defined in the methods object section. But if you want to make it global you can use plugins like below.
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App)
}).$mount("#app");
const MyPlugin = {
install(Vue, options) {
Vue.prototype.addNumbers = (a, b) => {
return a + b;
};
}
};
Vue.use(MyPlugin);
Then you can directly call the function in the template
<template>
<div>
<h1>{{addNumbers(1,2)}}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
methods: {
}
}
</script>
本文标签: javascriptVueJScall function in external JS file directly from TemplateStack Overflow
版权声明:本文标题:javascript - VueJS - call function in external JS file directly from Template - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744071035a2585886.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论