vue 中this.$set 动态绑定数据的案例讲解
这篇文章主要介绍了vue 中this.$set 动态绑定数据的案例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
感觉网上对this.$set的讲解乱糟糟的,我来总结一下对它单个数据、对象、数组、json数据的绑定.
话不多说直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <template> <div> <!-- 单个数据 --> <button @click= "text0a" >text0</button> <p>text0: {{text0}}</p> <!-- 对象 --> <button @click= "textObja" >textObj</button> <p>textObj.text1: {{textObj.text1}}</p> <!-- 数组 --> <button @click= "textArra" >textArr</button> <p>textArr[1]: {{textArr[1]}}</p> <!-- json数据 --> <button @click= "textJsona" >textJson</button> <p>textJson[1].t5: {{textJson[1].t5}}</p> </div> </template> <script> export default { data() { return { text0 : '' , textObj: {}, textArr: [], textJson:[ {t0: '' }, {t4: '' }, {t7: '' }, ] } }, methods: { text0a: function () { let vm = this let text100 = 'efghjk' vm.$set(vm, 'text0' ,text100) //等效于 vm.$set(vm,'text0','efghjk') }, textObja: function () { let vm = this let textObj100 = { text1: '123' , text2: '456' } vm.$set(vm.textObj, 'text1' ,textObj100.text1) //此时等效于 vm.$set(vm,'textObj',textObj100) }, textArra: function () { let vm = this let textArr200 = [ 'a1' , 'a2' , 'a3' ] vm.$set(vm, 'textArr' ,textArr200) }, textJsona: function () { let vm = this let textJson300 = [ {t1: 't1' ,t2: 't2' ,t3: 't3' }, {t4: 't4' ,t5: 't5' ,t6: 't6' }, {t7: 't7' ,t8: 't8' ,t9: 't9' }, ] vm.$set(vm.textJson[1], 't5' ,textJson300[1].t5) //此时等效于 vm.$set(vm,'textJson',textJson300) } } } </script> <style> </style> |
补充:Vue 使用$set动态给数据设置属性
在实际的开发过程中,给表单元素绑定model的时候,绑定的元素的属性是根据后台数据动态生成的。如果使用常规的赋值方式,是无法更新视图的
需要使用
1 | this .$set(dataName,keyName,keyValue) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | export default { data:{ // 先定义一个空对象 formObject:{}, arrayList:[], }, mounted() { this .initPage() }, methods:{ initPage(){ this .$store.dispatch(namespace/callData).then(res=>{ // 给数据设置key-value res.data.forEach(item=>{ // ❗❗❗❗❗ this.formObject[item.name] = item.value // ❗❗❗❗ 这种方式是不能更新视图的 this .$set( this .formObject, item.name, item.value) // ✅✅✅✅可以更新视图 }) }) // 修改数组 this .$store.dispatch(namespace/callData).then(res=>{ // 给数据设置key-value this .$set( this .arrayList,0,(res.data)[0].id) ✅✅✅✅可以更新视图 }) } } } |
以上为个人经验,希望能给大家一个参考