问题很简单。我想定义一个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
。我怎么做呢?
不能从data
设置道具的默认值。
computed
属性:
computed: {
defaultLogoURL: function() {
return this.infoLogoURL || this.logoURL
}
}
您可以定义一个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>