Vue.set()实现数据动态响应

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/qq_43168841/article/details/83003745

this.$set()和Vue.set()本质方法一样,前者可以用在methods中使用。

在vue里面,我们操作最多的就是各种数据,在jquery里面,我们习惯通过下标定向找到数据,然后重新赋值

比如var a[0]=111;

Vue.set()实现数据动态响应

下面上代码

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script src="./js/vue.min.js"></script>
</head>
<body>
 <div id="app">
 <ul>
 <li v-for="item in listData">{{item}}</li>
 </ul>
 <a href="javascript:void(0)" v-text="he" @click="changeData()"></a>
 </div>
</body>
<script>
 new Vue({
 el:"#app",
 data:{
 he:"点我",
 listData:["a","b","c"]
 },
 methods:{
 changeData () {
 this.listData[0]="d";
 }
 }
 })
</script>
</html>
</pre>

当我点击按钮时候,发现没有任何变化,页面上还是a,b,c

Vue.set()实现数据动态响应

下面是伟大的vue内置的方法来了

Vue.set() 官方解释: 设置对象的属性。如果对象是响应式的,确保属性被创建后也是响应式的,同时触发视图更新。这个方法主要用于避开 Vue 不能检测属性被添加的限制。

我的理解就是触发视图重新更新一遍,数据动态起来

Vue.set(a,b,c)

a是要更改的数据 b是数据的第几项 c是更改后的数据

解决上面数据不能更改后的代码

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script src="./js/vue.min.js"></script>
</head>
<body>
 <div id="app">
 <ul>
 <li v-for="item in listData">{{item}}</li>
 </ul>
 <a href="javascript:void(0)" v-text="he" @click="changeData()"></a>
 </div>
</body>
<script>
 new Vue({
 el:"#app",
 data:{
 he:"点我",
 listData:["a","b","c"]
 },
 methods:{
 changeData () {
 Vue.set(this.listData,0,'X')
 }
 }
 })
</script>
</html>
</pre>

我们可以看到,this.listData数组的第一项已经被更改了

Vue.set()实现数据动态响应
本次给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。

猜你喜欢

转载自blog.csdn.net/qq_43168841/article/details/83003745
今日推荐