VUE variable.length 在模板中工作,但给出控制台警告
VUE variable.length works in template, but gives console warning
我有一个模板,我需要在其中知道提供的变量的长度...
{{ prefix }} {{ prefix.length }}
它吐出正确的信息并且似乎工作正常,但它给出了这个警告:
[Vue warn]: Error when evaluating expression "{ input_prefix:
(prefix.length > 0)}": TypeError: Cannot read property 'length' of
undefined (found in component: )
我真的很想做对,去掉警告。有什么想法吗?
此致
约翰·拉杰
如果 prefix 为空或未定义,根据定义,它不能有长度。
因此,通过三元运算符呈现长度,如果前缀存在则使用长度 属性,如果前缀不存在则默认为零:
{{ prefix && prefix.length ? prefix.length : 0 }}
如 David 所指出的那样,当值为 null/undefined 时,您将面临问题。
我会使用计算变量来解决这个问题。
例如
new Vue({
el: '#app',
data: {
prefix: 'Some value'
},
computed: {
prefixLength: function(){
if(this.prefix){
return prefix.length
}
return '';
}
}
})
然后您只需在模板中使用它:
{{ prefix }} {{ prefixLength }}
new Vue({
el: '#app',
data: {
prefix: 'Some value'
},
computed: {
prefixLength: function(){
if(this.prefix){
return this.prefix.length
}
return '';
}
}
})
那么您只需在模板中使用它:
{{ prefix }} {{ prefixLength }}
我有一个模板,我需要在其中知道提供的变量的长度...
{{ prefix }} {{ prefix.length }}
它吐出正确的信息并且似乎工作正常,但它给出了这个警告:
[Vue warn]: Error when evaluating expression "{ input_prefix: (prefix.length > 0)}": TypeError: Cannot read property 'length' of undefined (found in component: )
我真的很想做对,去掉警告。有什么想法吗?
此致 约翰·拉杰
如果 prefix 为空或未定义,根据定义,它不能有长度。
因此,通过三元运算符呈现长度,如果前缀存在则使用长度 属性,如果前缀不存在则默认为零:
{{ prefix && prefix.length ? prefix.length : 0 }}
如 David 所指出的那样,当值为 null/undefined 时,您将面临问题。
我会使用计算变量来解决这个问题。
例如
new Vue({
el: '#app',
data: {
prefix: 'Some value'
},
computed: {
prefixLength: function(){
if(this.prefix){
return prefix.length
}
return '';
}
}
})
然后您只需在模板中使用它:
{{ prefix }} {{ prefixLength }}
new Vue({
el: '#app',
data: {
prefix: 'Some value'
},
computed: {
prefixLength: function(){
if(this.prefix){
return this.prefix.length
}
return '';
}
}
})
那么您只需在模板中使用它:
{{ prefix }} {{ prefixLength }}