【问题标题】:Vue JS - Changing data in created() and conditional renderingVue JS - 在 created() 和条件渲染中更改数据
【发布时间】:2021-06-20 00:33:20
【问题描述】:

我的组件中有一个变量alumnoIncoming,默认情况下是false,而在created() 中,我分配了一个作为查询通过路由器推送传递的值。我有一个 div,仅当该变量为 true 时才使用 v-if 有条件地呈现,但它始终呈现,即使它为 false。

当我用{{ alumnoIncoming }} 显示变量时,它的实际值是正确的,但如果我有条件地检查它,像这样:{{ alumnoIncoming ? "incoming" : "outgoing" }},它总是评估为真。

如果我使用单击按钮时执行的方法更改变量,则条件会正确更新。

这是我的组件的完整代码:

<template>
  <div>
    <div v-if="alumnoIncoming">
      esto solo se muestra si alumnoIncoming = true -> {{ alumnoIncoming }}
    </div>
    <div>
      <span >sin i18n : {{alumnoIncoming}} {{ alumnoIncoming ? "incoming" : "outgoing" }} </span>
    </div>
    <div >
    </div>
    <Button label="cambiar" @click="cambiar" />
  </div>
</template>

<script>
import Button from "primevue/button";

export default {
  data() {
    return {
      alumnoIncoming: false,
    };
  },
  created() {
    this.recibeParametros();
  },
  methods: {
    recibeParametros() {
      console.log(this.$route.query);
      this.alumnoIncoming = this.$route.query.alumnoIncoming;
    },
    cambiar() {
      this.alumnoIncoming = !this.alumnoIncoming;
    },
  },
  components: {
    Button,
  },
};
</script>

为什么第一次渲染组件时没有得到正确的变量值?

【问题讨论】:

  • {{ alumnoIncoming }} 的值是多少? v-if 测试真值,因此 1'asdf'、'{}'(空对象)、[](空数组)都将评估为真。除非alumnoIncomingfalse, '', undefined, null, NaN, or 0,否则v-if 将呈现该部分。
  • 好吧,你让我重新检查一下,如果我正确解析它,结果是路由器推送中作为查询传递的值是一个字符串,"true" 或“false”,而不是布尔值成功了,谢谢!

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

问题是在路由器推送中作为查询传递的值是一个字符串,而不是布尔值,所以它总是评估为真。为了解决这个问题,我们必须解析字符串:

    recibeParametros() {
      this.alumnoIncoming = (this.$route.query.alumnoIncoming === "true");
    },

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 2021-04-09
    • 2021-11-14
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2020-09-24
    相关资源
    最近更新 更多