javascript - 操作外部js文件中的Vue数据

标签 javascript vue.js

我正在从外部 js 文件导出一个函数,并尝试以这种方式操作 Vue 数据,但目前我无法做到这一点。这是我迄今为止尝试过的:

导入的js文件如下:

import * as device from "../Device"; 

调用如下方法:

device.playURL(this.currentTVChannelUrl,this.loading,this.isPlayerShown);

这是 device.js 文件中名为 playURL 的方法:

export function playURL(url,loading,isPlayerShown){
    player.play({
      uri: url,
    });
      loading = false;
      isPlayerShown = true;
}

它不会改变我的 Vue 组件的操作数据。有办法改变它们吗?

最佳答案

您可以将 playURL 的 this 上下文绑定(bind)到当前组件并使其正常工作。

let bindedplayURL = device.playURL.bind(this);
bindedplayURL(this.currentTVChannelUrl)
playURL(url) {
  player.play({
    uri: url,
  });
  this.loading = false /* changes data in vue component directly no need to pass these varibles separately */
  this.isPlayerShown = true;
}

但是,如果您创建 playURL 函数是为了在 Vue 文件内的各个位置使用它。我什至建议你看看 vue 中的 Mixins,它只解决这个目的,它们会智能地混合数据和方法本身。

关于javascript - 操作外部js文件中的Vue数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61523704/

相关文章:

vue.js - nuxt.js - 如何在服务器端为所有客户端缓存 axios 调用

google-chrome - 在 Vue Dev Tools (vue2/vuex3) 中未检测到 Vuex store

vue.js - Vuex 在异步操作完成之前访问状态

javascript - 点击确认然后重定向

JavaScript 迭代事件处理程序/监听器

javascript - jquery/javascript : return and if sentence

javascript - 美元前缀 ($) 在 Vue.js 中是什么意思?

javascript - 如何使用 Javascript 处理上传的文件

javascript - 如何将 "camelCase"转换为 "Camel Case"?

vue.js - vue js 中 main.js 中 axios 重试的响应