【问题标题】:Vuejs - How to set the default value of a prop to a predefined data?Vuejs - 如何将道具的默认值设置为预定义数据?
【发布时间】:2021-04-23 04:11:38
【问题描述】:

问题很简单。我想定义一个data如下;

data() {
  return {
    logoURL: "some-link/some-picture.png"
  }
}

我想将它设置为道具的默认状态,如下所示:

props: {
  infoLogoURL: {
    type: String,
    default: this.logoURL,
  },
}

显然它不能按我想要的方式工作,我有这个错误:

Uncaught TypeError: Cannot read property 'logoURL' of undefined

我该如何管理?这是我如何使用道具的示例:

<cardComp
  infoTitle = "Info Title" 
  infoText = "Info Text" 
  infoSubIcon = "Sub Icon Name" 
  infoSubIconColor = "css-color-class" 
  infoSubText = "Sub Text" 
  infoDescription = "Some Text Description" 
  infoIcon = "Icon Name" 
  infoIconColor = "icon-color-css"
  infoLogoURL = "some-link/some-picture.png"
/>

还有一个问题……我想在没有infoLogoURL 的情况下显示infoIcon。因此,假设某个特定 .png 文件的链接暂时不可用,那么在这种情况下,我想显示 infoIcon。当 .png 文件可用时,我应该只显示 infoLogoURL,而不是 infoIcon。我该怎么做?

【问题讨论】:

    标签: vue.js vue-props


    【解决方案1】:

    您不能设置来自data 的道具的默认值。

    解决此问题的一种方法是改用computed 属性:

    computed: {
      defaultLogoURL: function() {
        return this.infoLogoURL || this.logoURL
      }
    }
    

    【讨论】:

    • 感谢您回答问题!我会试试这个,然后告诉你。
    【解决方案2】:

    您可以定义一个computed 属性,该属性在设置时返回prop "info_logo_url" 的值,而在未设置时返回data "logoURL" 的值。

    关于问题的第二部分,可以定义另一个computed属性,设置时返回prop“info_logo_url”,不设置时返回prop“info_icon”。

    const cardcomponent = Vue.component('card-component', {
      template: '#card-component',
      data(){
        return { logoURL: "some-link/some-picture.png" }
      },
      props: {
        info_logo_url: { type: String },
        info_icon: { type: String }
      },
      computed: {
        myInfoLogo() { return this.info_logo_url || this.logoURL; },
        myInfoIcon() { return this.info_logo_url || this.info_icon; },
      }
    });
    
    new Vue({
      el: '#app',
      components: { cardcomponent },
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <div>
        <cardcomponent info_logo_url="info logo URL" info_icon="info icon"/>
      </div><hr>
      <div>
        <cardcomponent info_logo_url="info logo URL"/>
      </div><hr>
      <div>
        <cardcomponent info_icon="info icon"/>
      </div>
    </div>
    
    <template id="card-component">
      <div>
        <b>myInfoLogo</b>: {{myInfoLogo}} - <b>myInfoIcon</b>: {{myInfoIcon}}
      </div>
    </template>

    【讨论】:

    • 感谢回复,明天我会尝试使用计算出来的,如果可以的话告诉你。
    猜你喜欢
    • 2017-11-09
    • 2019-07-13
    • 2011-08-01
    • 2019-07-14
    • 2019-07-23
    • 2017-09-19
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多