Problem Description:
<template>
<p>
<section>{{x.a}}</section>
<section>{{x.b}}</section>
<section>{{x.c}}</section>
</p>
</template>
<script>
export default {
name:"xx",
data(){
return {
x:{
a:"foo",
b:null,
c:null
}
}
}
}
</script>
is rendered as
<p>
<section>foo</section>
<section></section>
<section></section>
</p>
Desired effect:
I hope there will be a global default value when the variable is not true, such as "--"
My attempt
<template>
<p>
<section>{{x.a||"--"}}</section>
<section>{{x.b||"--"}}</section>
<section>{{x.c||"--"}}</section>
</p>
</template>
Although this can achieve the effect, it is too tiring. Each one needs to be written down. Just to be lazy, I modified it
<template>
<p>
<section>{{showX("a")}}</section>
<section>{{showX("b")}}</section>
<section>{{showX("c")}}</section>
</p>
</template>
<script>
export default {
name:"xx",
data(){
return {
x:{
a:"foo",
b:null,
c:null
}
}
},
methods:{
showX:function(key){
const value = this.x[key];
return !!value?value:"--";
}
}
}
</script>
The help I want:
However, the above writing method still feels not convenient enough. Is there any way that I can still write <section>{{x.a}}</section> in the template and render it as "--" when its value is not true, provided that the original data x
You can use filter to achieve this effect:
If you still think it’s too troublesome, you can use more black-tech methods:
Explain,
_s
is an internal property of Vue. Every text node in the template will be processed by this method, and the return value will be rendered. Since it is an internal property, stability cannot be guaranteed when the version is updated. This is important. Notice. Demo attached:https://codepen.io/cool_zjy/p...
You can use the ternary operator,
This is equivalent to an if judgment statement,
Please provide me with your personal thoughts on where to modify the x value in data:
It is modified when creating, then it is enough to directly use the first short-circuit operation you used in the modified place
If you initialize the view and then modify it, then just set your initial value to '--', isn't it ok?