简体   繁体   English

如何从自定义 js 调用 function 到我的 Vue 组件方法

[英]How can I call a function from a custom js to my Vue component method

I'm trying to copy a drag and drop task like trello link我正在尝试复制像 trello 链接这样的拖放任务

Now, how can I call dragdrop.js 's function inside MyComponent.vue 's method?现在,如何在MyComponent.vue的方法中调用dragdrop.js的 function ?

Here's what I did...这就是我所做的......

MyComponent.vue我的组件.vue

  <template> 
    ....simple html drag and drop structure goes here
  </template>

  <script>
   import dragdrop from './dragdrop.js';
   export default {
       name: 'my-component',
       components: {},
       data: () => ({
          dragdrop : dragdrop
       }),
       methods: {
       dragStart(e) {
           this.dragdrop.dragStart(e);
       },
       dropIt(e) {
           this.dragdrop.dropIt(e);
       },
       allowDrop(e) {
           this.dragdrop.allowDrop(e);
       }
   }
  }
  </script>

dragdrop.js拖放.js

function dragStart(ev) {
    ....
}
function dropIt(ev) {
    ....
}
function allowDrop(ev) {
}

I got this error when I start dragging:开始拖动时出现此错误:

VM12491 tickets:36 Uncaught ReferenceError: dragStart is not defined
    at HTMLDivElement.ondragstart (VM12491 tickets:36)

VM12492 tickets:36 Uncaught ReferenceError: allowDrop is not defined
    at HTMLDivElement.ondragover (VM12491 tickets:36)

Firstly: you don't actually need to put the dragdrop in your data object.首先:您实际上不需要将拖放操作放入数据 object 中。 Here's a better way:这是一个更好的方法:

  <script>
   import { dropStart, dropIt, allowDrop } from './dragdrop.js'; // ES6 object destructuring

   export default {
       name: 'my-component',
       methods: {
         dragStart(e) {
             return dragStart(e);
         },
         dropIt(e) {
             return dropIt(e);
         },
         allowDrop(e) {
             return allowDrop(e);
         }
     }
  }
  </script>

Answer: My guess is that you should probably return the functions that you want to run.回答:我的猜测是您可能应该返回您想要运行的函数。 It's hard to tell what the actual problem is with the HTML drag attributes without the actual HTML code though.但是,如果没有实际的 HTML 代码,很难说出 HTML 拖动属性的实际问题是什么。

Export the function you need to use in the Vue component.导出Vue组件中需要使用的function。

const dragStart = function (ev) {
    console.log(ev);
};

export default dragStart;

Now you can import it in Vue like现在你可以像这样在Vue中导入它

import dragStart from "./dragdrop";

and can be used inside the component like并且可以在组件内部使用,例如

created() {
  dragStart('test');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM