Vue-22、总结Vue数据监测

1、功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue总结数据监测</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">
    <hr/>
    <h1 >学生信息</h1>
    <button @click="student.age++">年龄+1</button>
    <button @click="addsex">点击添加学生性别</button>

    <button @click="student.sex='女'">点击修改学生性别</button>

    <button @click="addFirstFriend">在列表首位添加一个朋友</button>
    <button @click="updateFirstName">修改第一个朋友的名字为张三</button>
    <button @click="addHobby">添加一个爱好</button>
    <button @click="updateHobby">修改第一个爱好为:开车</button>
    <h2>学生名字:{{student.name}}</h2>
    <h2 v-if="student.sex">性别:{{student.sex}}</h2>
    <h2>学生年龄:{{student.age}}</h2>

    <hr/>
    <h2>学生爱好</h2>
    <ul>
        <li v-for="p in student.hobby">{{p}}</li>
    </ul>
    <h2>学生朋友们</h2>
    <h2>
        <ul>
            <li v-for="(p,index) in student.friends" :key="index"> {{p.name}}--{{p.age}}</li>
        </ul>
    </h2>
</div>
<script type="text/javascript">
    Vue.config.productionTip=false;
    const vm = new Vue({
        el:"#root",
        data:{
            student:{
                name: 'tom',
                age:18,
                hobby:[
                    '抽烟',
                    '喝酒',
                    '烫头'
                ],
                friends:[
                    {name:'jeery',age:35},
                    {name:'tony',age:36}
                ]
            }
        },
        methods:{
            addsex(){
                // Vue.set(this.student,'sex','男')
                this.$set(this.student,'sex','男');
            },
            addFirstFriend(){
                this.student.friends.unshift({name:'李四',age:36});
            },
            updateFirstName(){
               this.student.friends[0].name="张三";
            },
            addHobby(){
                this.student.hobby.unshift('抽烟');
            },
            updateHobby(){
                this.student.hobby.splice(0,1,'开车');
               // Vue.set(this.student.hobby,0,'开车');
               // this.$set(this.student.hobby,0,'开车')
            },
        }
    })
</script>
</body>
</html>

2、总结

Vue-22、总结Vue数据监测_第1张图片

你可能感兴趣的:(vue,vue.js,前端,javascript)