5

vue报错Cannot read property 'checked' of undefined

父组件通过$refs调用子组件的方法,报错Error in v-on handler: "TypeError: Cannot read property 'checked' of undefined"加Cannot read property 'checked' of undefined

我是通过一个@click事件改变crmRewardUsersType 值为1(默认为0),下一行执行这句就报错了this.$refs.checkboxselect.checkedNum(this.selectedChkList);但第二次再点击就达到想要的效果了(通过后台传递回来的数据匹配对应项并选中)

具体代码如下:

子组件:

<template>
    <div>
        <div v-show="isCheckBoxShow">
            <label :for="item.id" v-for="(item, index) in usersTypes" :key="item.id">
                <input type="checkbox" :id="item.id" @click="count(item.id, item.name, index)" ref="chkb" :name="item.name" />{{ item.name }}
            </label>
        </div>
    </div>
</template>
<script>
export default {
    name: "CheckBoxSelect",
    props: {
        // 选项
        usersTypes: {
            type: Array,
        },
    },
    data() {
        return {
            isCheckBoxShow: false, // 下拉选项是否显示
            chkNum: 0, // 选中复选框数量
            chk: "",
        };
    },
    methods: {
        // 计算选中的checkbox数量和选中的项的id和name
        count(id, name, index) {
            var nums = 0;
            var chk = this.$refs.chkb;
            // console.log(chk);
            for (var i = 0; i < chk.length; i++) {
                if (chk[i].checked) {
                    nums++;
                }
            }
            this.chkNum = nums;
        },
     
        checked(selectedChkList) {
            if (selectedChkList.length != 0) {
                var chkLen = selectedChkList.length;
                this.chkNum = chkLen;
                this.chk = this.$refs.chkb;
                for (var i = 0; i < this.chk.length; i++) {
                    for (var j = 0; j < chkLen; j++) {
                        if (this.chk[i].name == selectedChkList[j]) {
                            this.chk[i].checked = true;
                        }
                    }
                }
            } else {
                this.chkNum = 0;
            }
        },
    },
};
</script>

父组件部分:

<CheckBoxSelect v-if="crmRewardUsersType == 1" :usersTypes="usersTypes" ref="checkboxselect" />

// 某个@click事件里的内容
this.crmRewardUsersType = 1;
this.$refs.checkboxselect.checked(this.selectedChkList); // selectedChkList为数组

 

查看全部
weixin_41359495
H_Franky
2020/12/04 23:48
  • html5
  • vue.js
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信

2个回复