Vue变量在组件内部变得未定义

时间:2020-04-15 13:12:10

标签: vue.js

我的变量在组件内部变得不确定,有人可以帮助我吗?

变量为:“ professor.nome”

基本上,我将我的“ professor”变量加载到carregarProfessores()方法中。

这是在所有内容之后加载Titulo组件的一种方法吗?

这是Thais未加载变量的组件:

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

3 个答案:

答案 0 :(得分:2)

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

首先不需要复制副本,只需在模板中使用道具本身即可。

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

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

答案 1 :(得分:0)

尝试

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'
      "
    />

答案 2 :(得分:0)

根据您的数据。 教授是数组,因此您无法直接访问Nome。

因此,您可以在Professor数组或

上进行迭代
<h1>{{ professor[0].nome }}</h1>