须要注意的地方css
因为方块变化框与下方ctrl部分共享一个动态参数counter,因此这两部分要包裹在同一个id之下,实现数据共享。html
给style添加绑定以后,因为样式参数要动态变化,因此直接将整个绑定的样式参数都放入computed中处理,返回值是一个样式的object。vue
/*html 片断*/ <li class="block" v-for="n in counter" v-bind:style="styleObject"></li> /*js 片断*/ data:{ counter:0, }, computed:{ styleObject : function(){ return { width: initWidth - this.counter * 20 +'px', } } }
附:完整代码函数
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Vue</title> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="ctrl"> <ul id="show" class="wrap"> <li class="block" v-for="n in counter" v-bind:style="styleObject"></li> </ul> <div class="wrap"> <button v-on:click="counter += 1">加一层</button> <p>这个按钮被戳了{{counter}}次</p> </div> </div> <script src="ventor/vue.js"></script> <script> var initWidth = 300; var vm = new Vue({ el:'#ctrl', data:{ counter:0, }, computed:{ styleObject : function(){ return { width: initWidth - this.counter * 20 +'px', } } } }) </script> </body> </html>
思路this
在v-for循环中,增长index参数,利用index对每一个block赋予不一样的宽度值。用v-if控制,当最后一块的宽度计算结果小于0的时候,中止循环生成,只计数,并显示提示。spa
在负责提示的p标签中添加v-if,让这个元素到了知足条件的时候才在DOM树中生成code
//html <div id="ctrl"> <ul id="show" class="wrap"> <li class="block" v-for="(n,index) in counter" v-if="index<11" v-bind:style="styleObject(index)"></li> </ul> <div class="wrap"> <button v-on:click="counter += 1">加一层</button> <p>这个按钮被戳了{{counter}}次</p> <p v-if="counter>10">{{warning}}</p> </div> </div>
注意htm
v-for里面的value、index参数,只在本身渲染的块中有效,没法在同一个实例下的其它地方使用。对象
//js var initWidth = 300; var vm = new Vue({ el:'#ctrl', data:{ counter:0, warning:'', }, methods:{ styleObject : function(index){ if(initWidth - index * 30>0){ return { width: initWidth - index * 30 +'px', } }else{ this.warning = '已经到最底层啦!'; return { width:0, } } } } })
注意blog
vm实例中,使用methods进行传参的函数调用(computed不具有传参的功能 )
v-bind:style 的methods函数要返回style键值对
双向数据绑定的数据对象不用写在return中
附:完整代码
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Vue</title> <link rel="stylesheet" href="css/index.css"> </head> <body> <!-- 倒金字塔--> <div id="ctrl"> <ul id="show" class="wrap"> <li class="block" v-for="(n,index) in counter" v-if="index<11" v-bind:style="styleObject(index)"></li> </ul> <div class="wrap"> <button v-on:click="counter += 1">加一层</button> <p>这个按钮被戳了{{counter}}次</p> <p v-if="counter>10">{{warning}}</p> </div> </div> <script src="ventor/vue.js"></script> <script> // 倒金字塔 var initWidth = 300; var vm = new Vue({ el:'#ctrl', data:{ counter:0, warning:'', }, methods:{ styleObject : function(index){ if(initWidth - index * 30>0){ return { width: initWidth - index * 30 +'px', } }else{ this.warning = '已经到最底层啦!'; return { width:0, } } } } }) </script> </body> </html>