繁体   English   中英

vuejs:第 3 方库中的“this”是“未定义的”

[英]vuejs : “this” in 3rd party library is “undefined”

我的第三方脚本具有以下格式的代码

(   function initialMethod(scope, factory) {
        // 'scope' here is UNDEFINED when used in Vue
        // but it is fine in React and Angular
    } (this, function function1(param1) {
              .....
             }       
      )          
    ....    
    function MyMethod() {....}
    ....
)

我使用以下方法从这个第三方库导入一个方法

import {MyMethod} from 'ThirdPartyScript'

当我在 React 或 Angular 中执行此操作时,它工作得非常好。

使用 Vue 时失败。 “范围”/“this”未定义。 示例 Vue 代码

<template>
    <div id="app">
       <p>Hello</p>
    </div>
</template>


<script>
    import {MyMethod} from 'ThirdPartyScript';

    export default {
        name: 'app',        
        created: function () {
          this.initApp();
        },
        methods: {
            initApp: function () {                
                //const myResult = MyMethod();
            } 
    }
</script>

一旦我包含第 3 方库的“import”语句(与我从中调用方法时相反),当我调用 import 语句时,我相信它会像 has () 一样执行“initialMethod”之后,就会出现此错误它告诉它执行。

为什么这在 Vue 中有所不同? 使用 Vue 时我必须设置不同的东西吗?

环境信息

我使用Vue CLI创建我的项目,package.json有以下版本提到

dependencies": {
    "core-js": "^2.6.5",
    "vue": "^2.6.10",        
},
"devDependencies": {
    "@vue/cli-plugin-babel": "^3.11.0",
    "@vue/cli-plugin-eslint": "^3.11.0",
    "@vue/cli-service": "^3.11.0",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "vue-template-compiler": "^2.6.10"
 },

更新

如果我将 3rd 方库中的“this”更改为“window”,我会走得更远,但现在在下面的电话中

const myResult = MyMethod();

我收到“MyMethod”的错误“对象(...)不是函数”

我终于解决了这个问题。

此问题仅在我的项目中有库的本地副本时出现(我在“脚本”下使用其他 javascript 实用程序文件)。

当我通过将库添加到 package.json/package-lock.json 来添加库然后运行“npm install”时,库加载正确,我不再看到任何错误

package.json

"dependencies": {
    "theLibrary": "https://.......",
    "core-js": "^2.6.5",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3"
},

封装锁.json

"dependencies": {
    ......
    "theLibrary": {
        "version": "https:.....",
         "integrity": ".....
    },
    ......
}

npm指令

npm install theLibrary 

暂无
暂无

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

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