- 在数据绑定中使用三元表达式:
<template>
<div>
<span>{{ isShow ? '显示' : '隐藏' }}</span>
</div>
</template>
<script>
export default {
data() {
return {
isShow: true
}
}
}
</script>
- 在计算属性中使用三元表达式:
<template>
<div>
<span>{{ displayText }}</span>
</div>
</template>
<script>
export default {
data() {
return {
text: 'Hello, World!'
}
},
computed: {
displayText() {
return this.text.length > 10 ? this.text.substring(0, 10) + '...' : this.text
}
}
}
</script>
- 在方法中使用三元表达式:
<template>
<div>
<button @click="toggle">{{ isShow ? '隐藏' : '显示' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
isShow: true
}
},
methods: {
toggle() {
this.isShow = !this.isShow
}
}
}
</script>
- 在条件渲染中使用三元表达式:
<template>
<div>
<span v-if="text ? true : false">{{ text }}</span>
<span v-else>No data</span>
</div>
</template>
<script>
export default {
data() {
return {
text: ''
}
}
}
</script>