javascript - Vue : how to pass a variable name as argument?

标签 javascript vue.js

我正在尝试创建一种方法来加载下载 JSON 文件并将内容分配给动态变量。我认为这应该可行,但 varA 和 varB 仍然为空:

  data() {
    return {
      varA: Array,
      varB: Array
    }
  },

  mounted(){
    this.loadJSON("example.com/fileA.json", this.varA);
    this.loadJSON("example.com/fileB.json", this.varB);
  },

  methods: {
    loadJSON(uri, target) {
      fetch(uri)
        .then(res => res.json())
        .then((out) => {
          target = out;
        })
        .catch(err => {
          throw err;
        });
    },
  }

我还尝试将 varA 和 varB 定义为计算属性,但结果相同。如何才能做到这一点,而无需在 loadJSON() 中对变量名称进行硬编码?

最佳答案

您可以使用Vue.set代替:

  mounted(){
    this.loadJSON("varA");
    this.loadJSON("varB");
  },

  methods: {
    loadJSON(uri, targetName) {
      const self = this;
      fetch(uri)
        .then(res => res.json())
        .then((out) => {
          Vue.set(self, targetName, out);
        })
        .catch(err => {
          throw err;
        });
    },
  }

关于javascript - Vue : how to pass a variable name as argument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472202/

相关文章:

javascript - Angular Bootstrap 选项卡 - 选择页面加载中调用的函数

javascript - 单击 iframe 中的按钮 > 在父窗口中隐藏 div

打开开发人员工具时,不会触发 Javascript onclick

javascript - 如何在输入文本字段中添加或增加数值?

vue.js - 如何从 Nuxt 商店导航到错误页面

vue.js - VueJS : Accessing data from within embedded component using inline-template

JavaScript 运行时错误 : Unable to get property 'innerHTML' of undefined or null reference in asp. 网络

vue.js - Nuxtjs如何在所有sass文件中添加全局环境变量

Vue.js + Webpack 我得到 setImmediate.js :80 Uncaught SyntaxError: Unexpected token ':'

css - 如何修复 Vue.js 过渡组中不同尺寸 img 的 v-align 样式?