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. jupyter-notebook - Mac下启动jupyter notebook后没有Python的选项?2. Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?3. css3 - 这个效果用 CSS 可以实现吗?border-image4. android - webview 自定义加载进度条5. 输入地址报以下截图错误,怎么办?6. javascript - vue更改当前节点元素7. vue.js - vue 打包后 nginx 服务端API请求跨域问题无法解决。8. mac连接阿里云docker集群,已经卡了2天了,求问?9. angular.js - angular post的Content-Type被设置,导致不能上传图片,求助!!10. 如何解决Centos下Docker服务启动无响应,且输入docker命令无响应?

网公网安备