javascript VueJS 在 vue 组件中访问外部导入的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49144933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:26:15  来源:igfitidea点击:

VueJS accessing externaly imported method in vue component

javascriptvue.jsvuejs2exportvue-component

提问by Pathum Kalhan

I have an External Java Script File something.js

我有一个外部 Java 脚本文件 something.js

function myFun(){
  document.getElementById("demo").innerHTML="Hello World!";
  }

export default myFun;

and this is my vue component Dashboard.vue

这是我的 vue 组件 Dashboard.vue

<template>
    <div>
        <button type="button" name="button" @click="">Call External JS</button>
        <div id="demo"></div>
    </div>
</template>

<script>
import something from "./something.js"
export default {

created(){
}
}
</script>

I have two questions.

我有两个问题。

  1. First how do I call this method inside the created life cycle hook to automatically run.
  2. Second how do I call this method by hitting the button "Call External JS"
  1. 首先我如何在创建的生命周期钩子中调用这个方法来自动运行。
  2. 其次,我如何通过点击“调用外部 JS”按钮来调用此方法

Of-cause I know to change the content of a div can easily done by vueJS without the help of pure JS external files. But I'm asking this question for clarify the concepts of how do I use external JS files inside the vue component.

因为我知道更改 div 的内容可以通过 vueJS 轻松完成,无需纯 JS 外部文件的帮助。但我问这个问题是为了澄清如何在 vue 组件中使用外部 JS 文件的概念。

Thank you.

谢谢你。

采纳答案by kingdaro

  1. You can straight-forwardly call the imported somethingfunction under any lifecycle method you want. Here, however, I'd recommend using the mountedmethod, as that's the one that triggers once all of the component's HTML has rendered.

  2. There are lots of ways to do this. One way would be to add the somethingfunction under the vue component's data, then call the function directly from the template.

    Personally, I'd make a method on the Vue component which calls the function, then have your template's @click call that method. Doing it this way allows you to perform other actions or call other functions in the future if you wanted to. It also just looks a little cleaner to me.

  1. 您可以something在您想要的任何生命周期方法下直接调用导入的函数。但是,在这里,我建议使用该mounted方法,因为一旦所有组件的 HTML 都已呈现,就会触发该方法。

  2. 有很多方法可以做到这一点。一种方法是something在 vue 组件的 下添加函数data,然后直接从模板调用该函数。

    就个人而言,我会在调用该函数的 Vue 组件上创建一个方法,然后让您模板的 @click 调用该方法。如果您愿意,这样做可以让您在将来执行其他操作或调用其他功能。它对我来说也看起来更干净一些。

With that in mind, you'd end up with this:

考虑到这一点,你最终会得到这个:

<template>
  <div>
    <button type="button" name="button" @click="callSomething">Call External JS</button>
    <div id="demo"></div>
  </div>
</template>

<script>
import something from "./something.js"

export default {
  mounted() {
    something()
  },
  methods: {
    callSomething() {
      something()
    }
  }
}
</script>

回答by Narxx

A better solution would be to to use mixins:

更好的解决方案是使用 mixins:

import something from './something.js'
export default {
  mixins: [something]
}

now you can use whatever methods / computed you have exported in something.js, directly on this.

现在你可以使用任何方法/计算机已在出口something.js上,直接this

So, in your example, you have myFun()exported from something.js, and we can call it from Dashboard.vuelike so:

因此,在您的示例中,您已从myFun()导出something.js,我们可以Dashboard.vue像这样调用它:

<template>
    <div>
        <button type="button" name="button" @click="myFun">Call External JS</button>
        <div id="demo"></div>
    </div>
</template>

<script>
    import something from "./something.js"
    export default {
        mixins: [something],
        mounted(){
            this.myFun()
        }
    }
</script>

I hope I got the syntax right, but that's generally the idea of mixins.

我希望我的语法正确,但这通常是 mixin 的想法。

回答by Kodiak

Another approach would be to add the method in the data-block:

另一种方法是在数据块中添加方法:

import something from "./something.js" // assuming something is a function

data() {
  return {
    // some data...
    something,
  }
}

Then in your template use it like:

然后在您的模板中使用它,例如:

<template>
    <div class="btn btn-primary" @click="something">Do something</div>
</template>

回答by Larry Mckuydee

With your example, external javascript file something.js

使用您的示例,外部 javascript 文件something.js

function myFun(){
   document.getElementById("demo").innerHTML="Hello World!";
}

export default myFun;

You can parse it like object in your methods:{} in Dashboard.vue

你可以在你的方法中像对象一样解析它:{} in Dashboard.vue

<template>
    <div>
        <button type="button" name="button" @click="something">Call External JS</button>
        <div id="demo"></div>
    </div>
</template>

<script>
import something from "./something.js"
export default {

   methods: {
      something,
   }
}
</script>

回答by Meet Zaveri

The methods which are reactive or coupled with the components(which are not API's) should be written in methods.I follow this practice. I have a scenario here to clarify your concepts:

响应式或与组件(不是 API 的)耦合的方法应该用methods.I编写。我遵循这种做法。我在这里有一个场景来澄清你的概念:

JS file(one with containing function)filename - apis.js

JS 文件(一个包含函数)文件名 - apis.js

export function GetApiCall(apiName, data, header) {
 return new Promise((resolve, reject) => {
    //do something here
  });
 }

I have used that function here in createdhook. Thing is you can use it one of the user-defined methods.

我在createdhook 中使用了这个函数。事情是您可以使用它作为用户定义的方法之一。

Vue file(one which we will use that function from js file) - filename - infoform.vue

Vue 文件(我们将从 js 文件中使用该函数的文件) - 文件名 - infoform.vue

 import { GetApiCall } from '../utils/apisget';
  export default{
    created(){
        // Invoked API to get Data of organization
        GetApiCall(URL,{},{
                "Content-Type": "application/json",
                "Authorization": 'Bearer ' + token
            })
            .then(responseJson => {
            })
            .catch(err=>{
                this.$toasted.show(err);
                // console.log('error==',err);
            });
    },
  methods: {
     onClickMethod () {
       GetApiCall(URL,{},{});
     }
  }
}