在我们进行Vue项目开发的过程中,当Vue实例生成后,想要再次给数据赋值时,有时候并不会自动更新到视图上。
比如:我们想给Vue实例data数据中的某个对象新增一个属性,但新增的属性有时候并不会自动更新到视图上,是因为Vue实例中的数据是响应式的,而我们新增的属性并不是响应式的,由于受现在JavaScript的限制,Vue无法检测到属性的新增或删除。所以有时无法实时的更新到视图上。
<template> <div> <div>首页</div> <div>姓名:{{student.name}}</div> <div>年龄:{{student.age}}</div> <button @click="homeHandle" style="cursor: pointer;">点击</button> </div> </template> <script> export default { name: "home", data() { return { student: { name: '小明' } } }, methods: { homeHandle() { this.student.age = 20;//给student新增一个属性age console.log(this.student); } } } </script> <style scoped> </style>
从上述例子我们就可以看出,我们给student对象新增了一个属性age,从打印的结果我们看到了student对象中确实新增了一个属性age,但是我们在视图上却没有看到这个属性age的值,因此我们新增的属性age并没有更新到视图上,所以没有看到age属性的值。
那我们该怎么给student对象新增一个属性age并能实时更新看到结果呢?Vue提供了一个Vue.set()方法可以解决这个问题。
(1)通过Vue.set方法
<template> <div> <div>首页</div> <div>姓名:{{student.name}}</div> <div>年龄:{{student.age}}</div> <button @click="homeHandle" style="cursor: pointer;">点击</button> </div> </template> <script> import Vue from 'vue'; export default { name: "home", data() { return { student: { name: '小明' } } }, methods: { homeHandle() { // this.student.age = 20; Vue.set(this.student, 'age', 20); console.log(this.student); } } } </script> <style scoped> </style>
(2) 通过this.$set实例方法,这也是全局 Vue.set方法的别名
<template> <div> <div>首页</div> <div>姓名:{{student.name}}</div> <div>年龄:{{student.age}}</div> <button @click="homeHandle" style="cursor: pointer;">点击</button> </div> </template> <script> export default { name: "home", data() { return { student: { name: '小明' } } }, methods: { homeHandle() { // this.student.age = 20; this.$set(this.student,'age',20); console.log(this.$set(this.student,'age',20));//返回值: 20 console.log(this.student); } } } </script> <style scoped> </style>
从上述例子我们可以看出,我们不仅给student对象新增了一个属性,而且同时视图上也看到了结果,达到了视图的实时更新。
Vue.set( target, propertyName/index, value ),返回值:设置的值
参数:
{Object | Array} target
{string | number} propertyName/index
{any} value
该方法接受3个参数:
参数1:target(可以是对象也可以是数组)
参数2:propertyName/index(新增属性名/数组下标)
参数3:value(新增的属性值/更改值)
Vue面试题:Vue中我改变了data中的一个值,但现在视图上没有实时更新,请问我怎么拿到更新后的值?(考察Vue中$set作用)
最新推荐文章于 2023-07-10 18:30:19 发布