Vue 学习二

1. 绑定样式

1.1 绑定 class 样式–字符串写法,适用于:样式的类名不确定,需要动态指定

<body>
<div id="root">
        <!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
        <div class="basic" :class="mood" @click="changeMood">{{name}}
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: 'hello, world',
            mood: 'normal',
        methods: {
            changeMood() {
                this.mood = 'happy'//改变normal样式为happy央视
                //随机选取样式
                //const arr = ['happy','sad','normal']
			    //const index = Math.floor(Math.random()*3)
			    //this.mood = arr[index]
            }

        }
    })

</script>

1.2 绑定class样式–数组写法,适用于:要绑定的样式个数不确定、名字也不确定

<body>
    <div id="root">
        <!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
        <div class="basic" :class="classArr">{{name}}
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: 'hello, world',
            classArr: ['atguigu1', 'atguigu2', 'atguigu3'],
        }
    })

</script>

1.3 绑定class样式–对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用

<body>
    <div id="root">
           <!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用 -->
        <div class="basic" :class="classObj">{{name}}
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: 'hello, world',
            classObj: {
                atguigu1: true,
                atguigu2: false
            }
        }
    })

</script>

1.4 绑定style样式–对象写法

<body>
    <div id="root">
           <!-- 绑定style样式--对象写法 -->
         <div class="basic" :style="styleObj">{{name}}
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: 'hello, world',
            styleArr: {
                fontSize: '40px',
                color: 'orange'
            }
        }
    })

</script>

1.5 绑定style样式–数组写法(用得较少)

<body>
    <div id="root">
           <!-- 绑定style样式--数组写法 -->
         <div class="basic" :style="styleArr">{{name}}
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: 'hello, world',
           styleArr:[
					{
						fontSize: '40px',
						color:'blue',
					},
					{
						backgroundColor:'gray'
					}
				]
    })
</script>

2. 条件渲染

2.1 v-if

写法:
(1)v-if =“表达式”
(2)v-else-if =“表达式”
(3)v-else =“表达式”

适用于:切换频率较低的场景。
特点:不展示的DOM元素直接被移除。
注意:v-if可以和:v-else-if、v-else一起使用,但要求结构不能被“打断”。

        <h2 v-if="false">欢迎来到{{name}}</h2>

        <h2 v-if="1 === 1">欢迎来到{{name}}</h2>
        <div v-if="n === 1">Angular</div>
        <div v-else-if="n === 2">React</div>
        <div v-else-if="n === 3">Vue</div>
        <div v-else>哈哈</div>
        <template v-if="n === 1">
            <h2>你好</h2>
            <h2>尚硅谷</h2>
            <h2>北京</h2>
        </template>

2.2 v-show

写法:v-show=“表达式”
适用于:切换频率较高的场景。
特点:不展示的DOM元素未被移除,仅仅是使用样式隐藏掉

<h2 v-show="false">欢迎来到{{name}}</h2>

<h2 v-show="1 === 1">欢迎来到{{name}}</h2>

注意:使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。

3. 列表渲染

3.1 基本列表遍历 V-for

v-for指令:

  1. 用于展示列表数据
  2. 语法:v-for=“(item, index) in xxx” :key=“yyy”
  3. 可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)
3.1.1 遍历数组
<body>
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表(遍历数组)</h2>
        <ul>
            <li v-for="(p, index) of person" :key="index">
                {{p.name}}-{{p.age}}
            </li>
        </ul>

    </div>

    <script>
        new Vue({
            el: '#root',
            data: {
                person: [
                    { id: '001', name: '张三', age: 18 },
                    { id: '002', name: '李四', age: 19 },
                    { id: '003', name: '王五', age: 20 }
                ],
            }

        })
    </script>
</body>

在这里插入图片描述

3.1.2 遍历对象
<body>
    <div id="root">
        <!-- 遍历对象 -->
        <h2>汽车信息(遍历对象)</h2>
        <ul>
            <li v-for="(value,k) of car" :key="k">
                {{k}}-{{value}}
            </li>
        </ul>
    </div>

    <script>
        new Vue({
            el: '#root',
            data: {
                car: {
                    name: '奥迪',
                    price: '70万',
                    color: '黑色'
                },

            }

        })
    </script>
</body>

在这里插入图片描述

3.1.3 遍历字符串
<body>
    <div id="root">
        </ul>
        <!-- 遍历字符串 -->
        <h2>测试遍历字符串(用得少)</h2>
        <ul>
            <li v-for="(number,index) of str" :key="index">
                {{index}}-{{number}}
            </li>
        </ul>


    </div>

    <script>
        new Vue({
            el: '#root',
            data: {
                str: 'hello'

            }

        })
    </script>
</body>

在这里插入图片描述

3.1.4 遍历次数
<body>
    <div id="root">
        <!-- 遍历指定次数 -->
        <h2>测试遍历指定次数(用得少)</h2>
        <ul>
            <li v-for="(number,index) of 5">
                {{index}}-{{number}}
            </li>
        </ul>


    </div>
</body>

在这里插入图片描述

3.2 key 的原理(面试题)

面试题:react、vue中的key有什么作用?(key的内部原理)

  1. 虚拟DOM中key的作用:
    key是虚拟DOM对象的标识,当数据发生变化时,Vue会根据【新数据】生成【新的虚拟DOM】, 随后Vue进行【新虚拟DOM】与【旧虚拟DOM】的差异比较,比较规则如下:

  2. 对比规则:
    (1).旧虚拟DOM中找到了与新虚拟DOM相同的key:
    ①.若虚拟DOM中内容没变, 直接使用之前的真实DOM!
    ②.若虚拟DOM中内容变了, 则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
    (2).旧虚拟DOM中未找到与新虚拟DOM相同的key,则创建新的真实DOM,随后渲染到到页面

  3. 用index作为key可能会引发的问题:
    1. 若对数据进行:逆序添加、逆序删除等破坏顺序操作:
    会产生没有必要的真实DOM更新 ==> 界面效果没问题, 但效率低。
    2. 如果结构中还包含输入类的DOM:
    会产生错误DOM更新 ==> 界面有问题。

  4. 开发中如何选择key?:
    1.最好使用每条数据的唯一标识作为key, 比如id、手机号、身份证号、学号等唯一值。
    2.如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,使用index作为key是没有问题的。

在这里插入图片描述

3.3 列表过滤

需求:根据名字搜索对应的人名
在这里插入图片描述

<body>
    <div id="root">
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <li v-for="(p,index) of filPerons" :key="index">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
    <script>

        //用computed实现
        new Vue({
            el: '#root',
            data: {
                keyWord: '',
                persons: [
                    { id: '001', name: '马冬梅', age: 19, sex: '女' },
                    { id: '002', name: '周冬雨', age: 20, sex: '女' },
                    { id: '003', name: '周杰伦', age: 21, sex: '男' },
                    { id: '004', name: '温兆伦', age: 22, sex: '男' }
                ],
            },
            computed: {
                filPerons() {
                    return this.persons.filter((p) => {
                        //所有字符串都包含空格
                        return p.name.indexOf(this.keyWord) !== -1
                    })
                }
            }

        })
    </script>
</body>

<body>
    <div id="root">
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <li v-for="(p,index) of filPerons" :key="index">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
    <script>
        //用watch实现
        new Vue({
            el: '#root',
            data: {
                keyWord: '',
                persons: [
                    { id: '001', name: '马冬梅', age: 19, sex: '女' },
                    { id: '002', name: '周冬雨', age: 20, sex: '女' },
                    { id: '003', name: '周杰伦', age: 21, sex: '男' },
                    { id: '004', name: '温兆伦', age: 22, sex: '男' }
                ],
                filPerons: []
            },
            watch: {
                keyWord: {
                    immediate: true,
                    handler(val) {
                        this.filPerons = this.persons.filter((p) => {
                            // 返回包含val的对象
                            return p.name.indexOf(val) !== -1
                        })
                    }


                }
            }
        })

    </script>
</body>

3.4 列表排序

<body>
    <div id="root">
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <button @click="sortType=1">年龄升序</button>
        <button @click="sortType=2">年龄降序</button>
        <button @click="sortType=0">原顺序</button>
        <ul>
            <li v-for="(p,index) of filPerons" :key="index">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
    <script>
        // 用computed实现
        new Vue({
            el: '#root',
            data: {
                keyWord: '',
                persons: [
                    { id: '001', name: '马冬梅', age: 19, sex: '女' },
                    { id: '002', name: '周冬雨', age: 20, sex: '女' },
                    { id: '003', name: '周杰伦', age: 21, sex: '男' },
                    { id: '004', name: '温兆伦', age: 22, sex: '男' }
                ],
                sortType: 0//0为原顺序,1为升序,2为降序
            },
            computed: {
                filPerons() {
                    const arr = this.persons.filter((p) => {
                        //所有字符串都包含空格
                        return p.name.indexOf(this.keyWord) !== -1
                    })
                    //按照年龄排序
                    if (this.sortType) {
                        arr.sort((p1, p2) => {
                            return this.sortType == 1 ? p1.age - p2.age : p2.age - p1.age
                        })
                    }
                    return arr
                }
            }

        })
    </script>
</body>

3.5 列表数据更新

	<script type="text/javascript">
			Vue.config.productionTip = false
			
			const vm = new Vue({
				el:'#root',
				data:{
					persons:[
						{id:'001',name:'马冬梅',age:30,sex:'女'},
						{id:'002',name:'周冬雨',age:31,sex:'女'},
						{id:'003',name:'周杰伦',age:18,sex:'男'},
						{id:'004',name:'温兆伦',age:19,sex:'男'}
					]
				},
				methods: {
					updateMei(){
						// this.persons[0].name = '马老师' //奏效
						// this.persons[0].age = 50 //奏效
						// this.persons[0].sex = '男' //奏效
						// this.persons[0] = {id:'001',name:'马老师',age:50,sex:'男'} //不奏效
						this.persons.splice(0,1,{id:'001',name:'马老师',age:50,sex:'男'})
					}
				}
			}) 

		</script>

3.6 v-set的使用

两种写法:

//第一种写法
Vue.set(this.元素,'属性','属性值')

//第二种写法
this.$set(this.元素,'属性','属性值')
<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		const vm = new Vue({
			el:'#root',
			data:{
				school:{
					name:'尚硅谷',
					address:'北京',
				},
				student:{
					name:'tom',
					age:{
						rAge:40,
						sAge:29,
					},
					friends:[
						{name:'jerry',age:35},
						{name:'tony',age:36}
					]
				}
			},
			methods: {
				addSex(){
					// Vue.set(this.student,'sex','男')
					this.$set(this.student,'sex','男')
				}
			}
		})
	</script>

3.7 Vue监视数据原理

Vue监视数据的原理:

  1. vue会监视data中所有层次的数据。

  2. 如何监测对象中的数据?
    通过setter实现监视,且要在new Vue时就传入要监测的数据。
    (1).对象中后追加的属性,Vue默认不做响应式处理
    (2).如需给后添加的属性做响应式,请使用如下API:
    Vue.set(target,propertyName/index,value) 或
    vm.$set(target,propertyName/index,value)

  3. 如何监测数组中的数据?
    通过包裹数组更新元素的方法实现,本质就是做了两件事:
    (1).调用原生对应的方法对数组进行更新。
    (2).重新解析模板,进而更新页面。

  4. 在Vue修改数组中的某个元素一定要用如下方法:
    1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
    2.Vue.set() 或 vm.$set()
    3.不能对数组直接进行复值操作,如hobby[0]=‘唱歌’

特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!

实例

<body>

    <div id="root">
        <h1>学生信息</h1>
        <button @click="student.age++">年龄+1岁</button> <br />
        <button @click="addSex">添加性别属性,默认值:男</button> <br />
        <button @click="student.sex = '未知' ">修改性别</button> <br />
        <button @click="addFriend">在列表首位添加一个朋友</button> <br />
        <button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button> <br />
        <button @click="addHobby">添加一个爱好</button> <br />
        <button @click="updateHobby">修改第一个爱好为:开车</button> <br />
        <button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br />
        <h3>姓名:{{student.name}}</h3>
        <h3>年龄:{{student.age}}</h3>
        <h3 v-if="student.sex">性别:{{student.sex}}</h3>
        <h3>爱好:</h3>
        <ul>
            <li v-for="(h,index) in student.hobby" :key="index">
                {{h}}
            </li>
        </ul>
        <h3>朋友们:</h3>
        <ul>
            <li v-for="(f,index) in student.friends" :key="index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>
    </div>
</body>


<script type="text/javascript">
    Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            student: {
                name: '李四',
                age: 18,
                hobby: ['画画', '游泳', '抽烟'],
                friends: [
                    { id: '001', name: 'Joy', age: '20' },
                    { id: '002', name: 'Cindy', age: '21' },
                    { id: '003', name: 'Bob', age: '16' }
                ]
            },

        },
        methods: {
            addSex() {
                this.$set(this.student, 'sex', '男')
            },
            addFriend() {
                this.student.friends.unshift({ id: '004', name: 'Anna', age: '19' })
            },
            updateFirstFriendName() {
                this.student.friends[0].name = '张三'
            },
            addHobby() {
                this.student.hobby.push('跳舞')
            },
            updateHobby() {
                this.student.hobby.splice(0, 1, '开车')
                //this.$set(this.student.hobby,0,'开车')
            },
            removeSmoke() {
                this.student.hobby = this.student.hobby.filter((p) => {
                    return p !== '抽烟'
                })
            }


        }
    })


</script>

4. 收集表单数据

在这里插入图片描述


<body>
    <div id="root">
        <form @submit.prevent="demo">
            账号:<input type="text" v-model="userInfo.account"><br><br>
            密码:<input type="password" v-model="userInfo.password"><br><br>
            年龄:<input type="text" v-model="userInfo.age"><br><br>
            性别:男<input type="radio" name="sex" value="meal" v-model="userInfo.sex"><input type="radio" name="sex"
                value="femeal" v-model="userInfo.sex"><br><br>
            爱好:
            学习 <input type="checkbox" v-model="userInfo.hooby" value="study">
            打游戏<input type="checkbox" v-model="userInfo.hooby" value="game">
            吃饭<input type="checkbox" v-model="userInfo.hooby" value="eat"><br><br>
            所属校区:<select v-model="userInfo.city">
                <option value="">请选择校区</option>
                <option value="beijing">北京</option>
                <option value="hebei">河北</option>
                <option value="tianjing">天津</option>
            </select><br><br>
            其他信息 <textarea v-model.lazy="userInfo.other"></textarea><br><br><!--lazy失去焦点再获得全部文字-->
            <input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="">用户协议</a><br><br>
            <button>提交</button>
        </form>


    </div>
</body>
<script>
    new Vue({
        el: '#root',
        data: {
            userInfo: {
                account: '',
                password: '',
                age: '',
                sex: '',
                hooby: [],
                city: '',
                other: '',
                agree: '',
            }


        },
        methods: {
            demo() {
                console.log(JSON.stringify(this.userInfo));

            }
        }
    })
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值