【问题标题】:Vue variable getting undefined inside componentVue变量在组件内部未定义
【发布时间】:2020-04-15 21:57:32
【问题描述】:

我的变量在组件内部未定义,有人可以帮助我吗?

变量是:“professor.nome”

基本上我在 carregarProfessores() 方法中加载我的“教授”变量。

这是在完成所有操作之后加载 Titulo 组件的一种方式吗?

这是未加载变量的组件:

    <Titulo
      :texto="
        professorId !== undefined
          ? 'Professor: ' + professor.nome
          : 'Todos os alunos'
      "
    />

如果我尝试像这样访问 var,则可以:

<h1>{{ professor.nome }}</h1>

这是我的 Vue 代码:

export default {
  components: {
    Titulo,
  },
  data() {
    return {
      professorId: this.$route.params.prof_id,
      nome: "",
      alunos: [],
      professor: [],
    };
  },
  created() {
    if (this.professorId) {
      this.carregarProfessores();

      this.$http
        .get("http://localhost:3000/alunos?professor.id=" + this.professorId)
        .then((res) => res.json())
        .then((alunos) => (this.alunos = alunos));
    } else {
      this.$http
        .get("http://localhost:3000/alunos")
        .then((res) => res.json())
        .then((alunos) => (this.alunos = alunos));
    }
  },
  props: {},
  methods: {
    carregarProfessores() {
      this.$http
        .get("http://localhost:3000/professores/" + this.professorId)
        .then((res) => res.json())
        .then((professor) => {
          this.professor = professor;
        });
    },
  },
};

这是 Titulo 组件:

<template>
  <div>
    <h1>{{ titulo }}</h1>
  </div>
</template>

<script>
export default {
  props: {
    texto: String,
  },
  data() {
    return {
      titulo: this.texto,
    };
  },
};
</script>

【问题讨论】:

  • 在Titulo组件中,可以使用texto参数访问,但需要在props中声明。
  • @parthjani7 我该怎么做?你能解释一下吗?谢谢!
  • 你能把Titulo的代码贴出来吗?
  • 当然!已发布。

标签: vue.js


【解决方案1】:

问题在于您的Titulo 组件是有状态的。它获取了属性texto 的初始值的副本,但在更改时不会更新它。

一开始不需要复制,直接在模板中使用道具本身即可:

<template>
  <div>
    <h1>{{ texto }}</h1>
  </div>
</template>

<script>
export default {
  props: {
    texto: String
  }
};
</script>

【讨论】:

    【解决方案2】:

    试试

    data() {
        return {
          professorId: this.$route.params.prof_id || null, // changed
          nome: "",
          alunos: [],
          professor: null, // changed
        };
      },
    

    然后

    <Titulo
          :texto="
            professorId && professor
              ? 'Professor: ' + professor.nome
              : 'Todos os alunos'
          "
        />
    

    【讨论】:

    • 感谢您的回答!我如上所述更改了代码,但现在我只有“Todos os alunos”。应该有的是“教授:”+professor.nome。
    • 一旦我已经在方法 carregarProfessores() 中加载了 Var
    【解决方案3】:

    根据您的数据。 教授是数组,所以你不能直接访问 nome。

    所以你有教授数组的迭代器或

    <h1>{{ professor[0].nome }}</h1>
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 2020-02-23
      • 2019-08-25
      • 2021-06-04
      • 2018-10-09
      • 2022-01-25
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多