vue的计算属性computed与checkboc的结合使用 (使用非常方便)

老规矩先看效果图:

html:代码

1 <input v-model="checkboxIdStr" value="2" type="checkbox" id="check1"><label for="check1">9610集货模式</label>
2 <input v-model="checkboxIdStr" value="3" type="checkbox" id="check2"><label for="check2">1210备货模式</label>

js:

let vm = new Vue({
            el: '#app',
            data: {
               obj:{
            id:null,
            name:null,
            
details:[{
              id:null,
              projectDetailType:null,
            }]

          }
            },
            created: function () {
                
            },
            computed: {
                checkboxIdStr:{
                    get:function () {
                        return this.obj.details !=null && this.obj.details.length>0 && this.obj.details[0].projectDetailType !=null ? this.obj.details[0].projectDetailType.split(',') : []
                    },
                    set:function (newValue) {
                        return this.obj.details[0].projectDetailType = newValue.length>0? newValue.join(','):null
                    }
                }
            },
})

说明:在于你勾选复选框之后它会触发计算属性checkboxIdStr的set函数,可是它厉害的地方就在于Vue 知道 get函数 依赖于 this.obj.details,因此当 this.obj.details[0].projectDetailType在set函数里面发生改变时,所有依赖 get函数也会被触发(不信的话,你可以把get函数的return给注释掉,再去勾选复选框,此时只会触发set函数,而不会触发get)于是checkboxIdStr 的绑定也会更新,那么结合起来使用的话,就出现了上图所示的效果。。。是不是很棒啊!!!

 vue官方介绍计算属性: https://cn.vuejs.org/v2/guide/computed.html#%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7

原文地址:https://www.cnblogs.com/time1997/p/13182261.html