感觉网上对this.$set的讲解乱糟糟的,我来总结一下对它单个数据、对象、数组、json数据的绑定.
话不多说直接上代码:

<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>

Logo

前往低代码交流专区

更多推荐