【问题标题】:Element UI Tree Data not updating with Vue元素 UI 树数据未使用 Vue 更新
【发布时间】:2019-09-09 20:07:00
【问题描述】:

我创建了以下 vue 组件。

当我在 ajax 响应后更新时,以下代码不会更新数据。

更新数据后我需要应用任何特定方法吗?

我正在使用基于类的 vue cli 3 组件。它也没有给出任何错误。只是数据没有更新。

我们需要使用什么方法让 vue 反应性来更新数据或挂载的事件不起作用?

即使我将空数组作为子数组,名称也不会更新。

<template>
      <el-tree :data="MyData" :props="defaultProps"></el-tree>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ElemUI from 'element-ui';
import axios from 'axios';

@Component({
  components: {
    ElTree: ElemUI.Tree,
  },
})
export default class In extends Vue {
  public MyData: any = [
          {
            label: 'Data',
            children: [],
          },
        ];
  public defaultProps: any = {
    children: 'children',
    label: 'label',
  };
  public mounted() {
    axios
      .post('https://localhost:44375/api/Graph', {
        query: `{
                myData {
                    name,
                    innerData {
                    name
                    }
                  }
                }`,
      })
      .then((response) => {
        this.MyData = [
          {
            label: 'Another Data',
            children: Response.data.data.AnotherArrayData
          },
        ];
      });
  }
}
</script>

【问题讨论】:

  • 建议将 axios 调用定义为一个方法,然后使用 this.methodName() 在mounted hook 中调用该方法,该方法应该是一个等待 axios 解析的异步,因为它是一个承诺。
  • @I'mOnlyVueman。即使我不使用 axios,数据也不会更新。如果我将这段代码复制到 stackblitz,它就可以工作。不知道我的代码有什么问题。
  • 我尝试创建另一个函数并在mounted中调用它。仍然没有运气。
  • 你可以尝试切换mounted到created吗?这可能会有所不同,因为 created 会在 DOM 挂载之前触发数据检索。此外,请确保您的 axios 调用写为 async / await,因为它返回一个 Promise。类似async method(){ await axios... } .. 最后一件事是console.log 您的回复,以确保您使用实际数据设置数据。我知道你的服务器级别 res.send 是什么样的,但这也可能是问题所在。
  • 是的……!!! Mounted To Created 工作...!!!非常感谢伙计。请添加答案。 :)

标签: typescript vue.js vue-component element-ui


【解决方案1】:

所以要解决这个问题,让 axios 调用异步,然后加载到创建的钩子上,使用

methods: {
   async fetchDataMethod() {
      await axios...
  }
}`

`created() {
   this.fetchDataMethod();
}

这将在虚拟 DOM 挂载之前填充响应数据。

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多