VueJS访问Vue组件中的外部导入方法 [英] VueJS accessing externaly imported method in vue component

查看:945
本文介绍了VueJS访问Vue组件中的外部导入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an External Java Script File something.js

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

export default myFun;

这是我的Vue组件 Dashboard.vue

and this is my vue component 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>

我有两个问题.

  1. 首先,我如何在创建的生命周期挂钩中调用此方法以自动运行.
  2. 第二个如何通过点击调用外部JS"按钮来调用此方法的方法

原因是我知道通过vueJS可以轻松地更改div的内容,而无需纯JS外部文件的帮助.但是我问这个问题是为了阐明如何在vue组件中使用外部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.

谢谢.

推荐答案

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

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

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

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

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

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.

考虑到这一点,您最终会得到以下结果:

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>

这篇关于VueJS访问Vue组件中的外部导入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆