小白Vue之自我巩固,拆分代码初试
1 <style> 2 button { 3 background: blue; 4 height: 32px; 5 width: 120px; 6 border: 1px solid blue; 7 color: #FFFFFF; 8 margin-top: 20px; 9 font-size: 14px; 10 } 11 </style> 12 <body> 13 <!--实现:点击“添加”按钮 给list动态添加值,且每次的值都是input中的值--> 14 <div id="root"> 15 <input type="text" name="" id="" v-model="msg" /> 16 <button @click="add">添加</button> 17 <!--list显示--> 18 <ul> 19 <li v-for="(item,index) of list" :key="index">{{item}}</li> 20 </ul> 21 <!--侦听器--> 22 <div>{{count}}</div> 23 </div> 24 <script type="text/javascript"> 25 new Vue({ 26 el: "#root", 27 data: { 28 msg: "", 29 list: [], 30 count:0 31 }, 32 methods: { 33 add: function() { 34 this.list.push(this.msg); 35 this.msg=""; 36 } 37 }, 38 watch:{ 39 list:function(){ 40 this.count++; 41 } 42 } 43 }); 44 </script> 45 </body>
1 <!--实现:点击“添加”按钮 给list动态添加值,且每次的值都是input中的值--> 2 <div id="root"> 3 <input type="text" name="" id="" v-model="msg" /> 4 <button @click="add">添加</button> 5 <!--list显示--> 6 <ul> 7 <!--可以用vue提供的component的方法拆分组件。代码如下,但是如果只是这样的话,页面中只会显示一个item内容。我想要多个展示怎么办呢?--> 8 <!--<li-cell></li-cell>--> 9 10 <!--想要多个展示的话,写法一样使用v-for循环加载数据,虽然这样实现了页面中展示多个item,但是你会发现无论你在input中写什么点击添加后,页面展示的永远是item。那改怎么办呢?别着急我们往下继续看--> 11 <!--<li-cell v-for="(item ,index) of list" :key="index" ></li-cell>--> 12 13 <!--如果想要实现最初的实现效果的话,则我们可以进一步处理,如下:我们在li中再新增一个content属性,其值是每一项显示的内容item ,此时我们就可以把模板中的item换成content了--> 14 <li-cell v-for="(item ,index) of list" :key="index" :content="item"></li-cell> 15 </ul> 16 </div> 17 <script type="text/javascript"> 18 // 全局组件 19 Vue.component('li-cell', { 20 props: ['content'], // 添加content属性后,此处的意思是接收content属性,否则会报错 21 // template:"<li>item</li>" 之前 22 template: "<li>{{content}}</li>" // 添加content属性后 23 }); 24 // 另外想要使用局部组件的话,可以声明一个局部组件并在实例中新增components属性。可将全局组件注释放出局部组件查看效果。 25 // var cell={ 26 // props:['content'],// 接收content属性 27 // template:"<li>{{content}}</li>" 28 // }; 29 new Vue({ 30 el: "#root", 31 data: { 32 msg: "", 33 list: [], 34 }, 35 // components:{// 局部组件 36 // "li-cell":cell 37 // }, 38 methods: { 39 add: function() { 40 this.list.push(this.msg); 41 this.msg = ""; 42 } 43 } 44 }); 45 </script>