不管的原生开发仍是weex开发,常常会须要咱们对一些组件/控件动态赋值,在原生中,咱们你们都知道,对控件setText就能够了,那么在weex中呢,咱们须要怎么作呢,其实很简单,几行代码就能够搞定!
首先呢,须要知道一个概念叫“数据绑定”,即组件会根据内容的变化从新进行渲染,先看一下效果展现及代码:weex
<template> <div style="justify-content: center;align-items: center;flex-direction: column"> <text style="font-size: 30px;color: blue">{{mValue}}</text> <div style="background-color: aqua;width: 300px;height: 60px;align-items: center;justify-content: center;margin-top: 40px" @click="clickMe"> <text style="font-size: 30px;color: #000;">点我啊!!!</text> </div> </div> </template> <style> </style> <script> var navigator = weex.requireModule('navigator'); navigator.setNavBarTitle({'title': ''}, null); export default{ data: { mValue: '点击以前的文案' }, methods: { clickMe:function(){ this.mValue = '点击以后的文案'; } }, created: function () { }, mounted: function () { } } </script>
text标签经过“{{mValue}}”绑定数据,为了页面不展现空白,在data里面设置默认值,这个默认值能够为任意数据,再经过为div设置点击事件,动态的控制text的内容,很简单吧!!!
那若是需求不单单是动态的改变文案的内容呢,若是产品要求内容变化的同时,text的背景颜色也要变化呢,一样的道理,经过数据绑定,为text标签绑定一个背景的样式,点击div,文案和背景同时变化:flex
<template> <div style="justify-content: center;align-items: center;flex-direction: column"> <text :class="showWhich ? bg_style : bg_style1" style="font-size: 30px;color: blue">{{mValue}}</text> <div style="background-color: aqua;width: 300px;height: 60px;align-items: center;justify-content: center;margin-top: 40px" @click="clickMe"> <text style="font-size: 30px;color: #000;">点我啊!!!</text> </div> </div> </template> <style> .bgOne{ background-color: #afddff; } .bgTwo{ background-color: chartreuse; } </style> <script> var navigator = weex.requireModule('navigator'); navigator.setNavBarTitle({'title': ''}, null); export default{ data: { mValue: '点击以前的文案', bg_style:['bgOne'], bg_style1:['bgTwo'], showWhich:true }, methods: { clickMe:function(){ this.mValue = '点击以后的文案'; this.showWhich = false; } }, created: function () { }, mounted: function () { } } </script>
其实道理都是同样的,首先给text设置一个默认的背景样式,我这里只写了一个背景颜色,而后经过一个布尔类型的变量来控制显示哪一种样式,触发点击事件,会改变布尔变量的值,进而渲染不一样的背景ui
红色标记的这行代码就是一句三目运算,showWhich为true,渲染bg_style的背景,反之渲染bg_style1背景。this
其实没什么难度,若是有不理解或不清楚的地方,欢迎评论提疑!!!spa