微信小程序 使用三元运算符动态渲染布局
今天在写微信小程序时,被坑到了,
<!--.wxml->
<view class="row-in {{to_top ? 'to-top' : 'to-bottom'}}">
...
</view>
本意是想做一个简单的动态页面的,在用户点击按钮的时候,菜单会进行一个上滑置顶:
/*.wxss*/
.row-in {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #f3f2f27c;
}
.to-bottom {
padding: 320rpx 0 10rpx 0;
}
.to-top {
padding: 30rpx 0 10rpx 0;
}
//.js
Page({
data: {
to_top: false,
}
})
调试的时候发现不管怎么改这个三元运算符,它显示的都只是‘:’前的那个,如代码中的'to-top'。
改了很久,不知道问题在哪里,百度也没有找到解决办法。
只好换一种写法:
<!--.wxml->
<view class="{{to_top}}">
...
</view>
/*.wxss*/
.row-in {
}
.to-bottom {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #f3f2f27c;
padding: 320rpx 0 10rpx 0;
}
.to-top {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #f3f2f27c;
padding: 30rpx 0 10rpx 0;
}
//.js
Page({
data: {
to_top: "to-top",
}
})
如上修改后问题解决了,但用不了三元运算符还是很不满意。
个人猜测可能是代码在动态加载时的次序先后,导致的这个问题。如果知道是为什么,怎么解决的朋友欢迎留言告诉我,感谢!
2019-1-8补充(解决问题)
wxml
<view class="{{to_top}}">
</view>
<button bindtap='change_position'>改变位置</button>
wcss
.to-bottom {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #000;
padding: 320rpx 0 10rpx 0;
}
.to-top {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #000;
padding: 30rpx 0 10rpx 0;
}
js
Page({
data: {
to_top: "to-top",
},
change_position: function(){
var that = this
console.log("change position " + that.data.to_top)
this.setData({
to_top: that.data.to_top == "to-top" ? "to-bottom":"to-top"
})
}
})
上面的页面在运行时是成功的:
使用三元运算符:
<view class="{{to_top ? 'to-top' : 'to-bottom'}}">
</view>
<button bindtap='change_position'>改变位置</button>
.to-bottom {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #000;
padding: 320rpx 0 10rpx 0;
}
.to-top {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #000;
padding: 30rpx 0 10rpx 0;
}
Page({
data: {
to_top: false,
},
change_position: function(){
var that = this
console.log("change position " + that.data.to_top)
this.setData({
to_top: that.data.to_top ? false:true
})
}
})
运行时也成功了:
使用style设置:
<view class="to-top" style='padding-top: {{to_top? "30rpx":"320rpx"}};'>
</view>
<button bindtap='change_position'>改变位置</button>
.to-top {
display: flex;
flex-direction: row;
justify-content: space-around;
background: #000;
padding: 30rpx 0 10rpx 0;
}
Page({
data: {
to_top: false,
},
change_position: function(){
var that = this
console.log("change position " + that.data.to_top)
this.setData({
to_top: that.data.to_top ? false:true
})
}
})
最后也成功了,我记不得当时是不是忘记了用setData。但是现在使用已经都无误了。这种动态改变布局的方法配合上pisition的设置是可以做出很漂亮的布局的。
既然问题解决了,我就把博客名字改成,使用三元运算符动态渲染了。
最后非常感谢weixin_43954744
在评论留言提示。
版权声明
本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途
发布时间:2018年08月22日 20:33:46
备案号:
闽ICP备19015193号-1
关闭特效
评论区#
还没有评论哦,期待您的评论!
引用发言