javascript - vue模板中變量非真時的默認值
問題描述
問題描述:
<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>
渲染出來為
<p> <section>foo</section> <section></section> <section></section></p>
期望的效果:希望在變量非真時有全局默認值,比如'--'
我的嘗試
<template> <p><section>{{x.a||'--'}}</section><section>{{x.b||'--'}}</section><section>{{x.c||'--'}}</section> </p></template>
這樣雖然可以達到效果 但是太累。每個都要寫一筆。為了偷懶 我改造了一下
<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>
想得到的幫助:但是,上述寫法還是覺得不夠方便。有沒有什么辦法 使我可以在模板里還是寫<section>{{x.a}}</section> 當其值非真時渲染成'--' ,前提是不要污染原始數據x
問題解答
回答1:可以用 filter 來實現這個效果:
new Vue({ data: { message: ’’ }, filters: { e (str) { return str || ’--’ } }})
{{ message | e }}
如果還覺得太麻煩,可以用比較黑科技的手段:
var _s = Vue.prototype._sVue.prototype._s = function (s) { return _s.call(this, s || ’--’)}
解釋一下,_s 是 Vue 的內部屬性,模版中的每一個文本節點都會被這個方法處理,將返回值進行渲染,由于是內部屬性,所以在版本更新時不能保證穩定性,這點要注意。附上 Demo:https://codepen.io/cool_zjy/p...
回答2:可以運用三目運算符吧,
{{x.a?x.a:’--’}}
這個就是相當于一個if判斷語句,
回答3:提供個人思路吧,在于你在什么地方去修改data中的x值:
在created時修改,那么直接在修改的地方使用你第一種使用過的短路運算就足夠了
如果是初始化視圖后再修改,那么就設置你的初始為 ’--’, 不就可以嗎?
相關文章:
1. css3 - 沒明白盒子的height隨width的變化這段css是怎樣實現的?2. java - 根據月份查詢多個表里的內容怎么實現好?3. python3.x - c++調用python34. javascript - 在 model里定義的 引用表模型時,model為undefined。5. php工具中的mysql還是5.1以下的,請問如何才能升級到5.1以上?6. css3 - 這個右下角折角用css怎么畫出來?7. atom開始輸入!然后按tab只有空格出現沒有html格式出現8. javascript - 移動端自適應9. android - 課程表點擊后浮動后邊透明可以左右滑動的界面是什么?10. apache - 想把之前寫的單機版 windows 軟件改成網絡版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設服務器呢?
