【问题标题】:If/else statement in vuejs computed not workingvuejs 中的 if/else 语句计算不工作
【发布时间】:2021-05-10 15:35:39
【问题描述】:
    prop: ['type', 'alertSubject'],
    computed: {
         alertTitle() {
            let title = ""
            if(this.alertSubject == "requestStatusUpdate") {
                if(this.type == 'success') {
                    title = 'Status update is requested'
                }
                else if(this.type == 'waiting') {
                    title = 'Requesting status update'
                }
                else if(this.type == 'error') {
                    title = 'Status update not sent'
                }
                
            }
            return title
        },
   }

我觉得这应该可以工作,但事实并非如此。我所有的计算值只返回“title”的起始值。我错过了什么明显的东西吗?

编辑:我错过了一些明显的东西,我是个白痴。抱歉浪费大家的时间,我在“道具”上少了一个“s”

【问题讨论】:

  • 你确定this.alertSubject == "requestStatusUpdate" 是真的吗?
  • 是的,我在我的开发工具中使用了 Vue 插件,我可以看到传入的道具是什么
  • 试试 this.$props.alertSubject 和 this.$props.type
  • 我试过你的建议,它返回了一个错误"TypeError: Cannot read property 'alertSubject' of undefined"

标签: vue.js


【解决方案1】:

你的代码运行正常,就像这个 sn-p:

<html>

<head>

</head>

<body>

  <div id="container">
    Try "success", "waiting" or "error": <input type="text" id="container" placeholder="enter text" v-model="type">
    <p>{{ value }}</p>
    Message: {{alertTitle}} ...
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.10/vue.min.js"></script>
  <script>
    new Vue({
      el: '#container',
      data: {
        alertSubject: "requestStatusUpdate", // Fake prop
        type: "success", // Fake prop
      },
      computed: {
        alertTitle() {
          let title = ""
          if (this.alertSubject == "requestStatusUpdate") {
            if (this.type == 'success') {
              title = 'Status update is requested'
            } else if (this.type == 'waiting') {
              title = 'Requesting status update'
            } else if (this.type == 'error') {
              title = 'Status update not sent'
            }
          }
          return title
        },
      }
    });
  </script>

</body>

</html>

this.alertSubjectthis.type 都不存在。

像这样打印这些值

<div>
 alertSubject: {{alertSubject}}
 type: {{type}}
</div>

以便您查看值是否存在。

【讨论】:

  • 通过使用 Vue 开发工具,我可以看到这些道具确实具有价值并且当前确实存在。所以不会是这样:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 2019-03-01
相关资源
最近更新 更多