【问题标题】:Manipulate Vue data in an external js file在外部 js 文件中操作 Vue 数据
【发布时间】:2020-04-30 12:44:16
【问题描述】:

我正在从外部 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 组件的操作数据。有没有办法改变它们?

【问题讨论】:

  • 您可以在您的 Vue root 实例中添加 playURL eventsdispatch 从您的子组件中添加它

标签: javascript vue.js


【解决方案1】:

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

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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多