我正在从外部 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/