Vue3实现列表循环

今天小编和大家一起在Vue的路上探索,要实现的功能是这样的。现将默认 数组内的渲染到页面上,然后点击按钮之后,将文本框内的数据添加到列表上,效果如下

 

 

源码是这样的,下面我就结合代码中的注释来说明一下核心的代码

Vue.createApp({
    data(){
        return {
            list:['item1','item2','item3','item4'], // 绑定v-for循环的列表
            inputVal:""  // 绑定文本框的内容
        }
    },
    methods:{
        handleAddItem(){ // 绑定按钮的点击事件
            this.list.push(this.inputVal) // 修改绑定的数据,在数组中增加数据
            this.inputVal = '' // 对绑定的值重新赋值,清空文本框内的值
        }
    },
    template:`
        <div>
            // 通过v-model绑定表单元素的值,也就是常说的数据双向绑定
            <input v-model="inputVal" />
            // v-on:click是绑定按钮的点击事件,可以通过@click语法糖来替代
            <button v-on:click="handleAddItem">增加</button>
            <ul>
                // v-for和上一篇文章的v-if类似,都叫做指令
                // v-for用作数据的循环
                // v-for可以接受两个参数,第一个是数组中元素,第二个元素是下标
                // 可以通过in和of两个关键字链接绑定的变量
                // 不建议将v-if和v-for用在同一个元素上。非要用可以在外面嵌套div或者其他元素
                // 根据官方文档,同时使用的时候,v-for的优先级会高于v-if
                <li v-for="(item,index) of list">{{item}}</li> 
            </ul>
        </div>
        `
}).mount('#root')

之前有过基础或者细心的小伙伴会发现,小编在使用v-for的时候,后面用的是of关键字,那对于v-for来说,虽然官方文档给的是in,那么of和in有什么不一样呢?在原生js中,对于循环来说,可以使用关键字in和for来循环,得到的结果是不一样的,就像这样

let arr = [
  {name:'lilei',age:12},
  {name:'hanmeimei',age:20}
]
for(let item of arr){
  console.log(item)  // {{name:'lilei',age:12}  {name:'hanmeimei',age:20}
}

for(let key in arr){
  console.log(item) // 0  1
}

小编在查询了一些资料后,得到这样的结论,遍历数组的时候,推荐使用of,语法为(item,index)。在遍历对象的时候,推荐使用in,语法为(item,name,index)下面是实例

DATA:
    list:[
        {name:'1'},
        {name:'2'},
        {name:'3'},
    ]

html:
<div class="items" v-for='(item,name,index) of list'>{{item}}->{{name}}->{{index}}</div>
<div class="items" v-for='(item,name,index) in list'>{{item}}->{{name}}->{{index}}</div>

// 输出结果如下
{ "name": "1" }->0->
{ "name": "2" }->1->
{ "name": "3" }->2->

{ "name": "1" }->0->
{ "name": "2" }->1->
{ "name": "3" }->2->
DATA:
    listObject:{
        name:'soho',
        age:25,
        class:1909,
        grade:3
    } 

html:
<div class="items" v-for='(item,name,index) of listObject'>{{item}}->{{name}}->{{index}}</div>
<div class="items" v-for='(item,name,index) in listObject'>{{item}}->{{name}}->{{index}}</div>

// 输出结果为
soho->name->0
25->age->1
1909->class->2
3->grade->3

soho->name->0
25->age->1
1909->class->2
3->grade->3

参考文章:

https://vue3js.cn/

https://www.cnblogs.com/Scooby/p/12160313.html

posted @ 2021-08-25 16:49  飞鹰3995  阅读(836)  评论(0编辑  收藏  举报