继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

慕的地10843
关注TA
已关注
手记 1081
粉丝 200
获赞 961

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

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

比如var a[0]=111;

webp

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

webp

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数组的第一项已经被更改了

webp

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



作者:前端攻城小牛
链接:https://www.jianshu.com/p/8fe56e47179d


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP