Vue学习(v-for)

循环语句

循环使用 v-for 指令。

v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。

v-for 可以绑定数据到数组来渲染一个列表:(简单做个添加商品的应用)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>

<body>

    <div id="app">
        <label>
            ID:<input type="text" v-model="id">
        </label>
        <label>
            Name:<input type="text" v-model="name">
        </label>
        <label>
            Price:<input type="text" v-model="price">
        </label>
        <input type="button" value="添加" @click="add">
        <table border="1px" style="width: 800px;text-align: center">
            <thead>
                <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>price</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in list" :key="item.id"><!--加上key指定唯一性-->
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <script>
        var v = new Vue({
            el:"#app",
            data:{
                id:'',
                name:'',
                price:'',
                list:[
                	//以下是固定的数据
                    {id:1,name:'john',price:12},
                    {id:2,name:'apple',price:12},
                    {id:3,name:'banana',price:12},
                    {id:4,name:'egg',price:12},
                    {id:5,name:'table',price:12}
                ]
            },
            methods:{
                add(){//绑定的按钮事件执行一下添加
                	//局部要用this引用,通过输入框传入的数据渲染到表格上
                    this.list.push({id:this.id,name:this.name,price:this.price})
                    //添加完之后默认输入框为空
                    this.id='';
                    this.name='';
                    this.price='';
                }
            }
        })
    </script>

</body>
</html>

在这里插入图片描述
我们通过在输入框上输入值,点击添加按钮把输入框的值渲染到表格上
在这里插入图片描述
在这里插入图片描述

发布了184 篇原创文章 · 获赞 864 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/Woo_home/article/details/101057440