VUE自定义组件使用测试多选框组
在定义组件有些地方需要注意的,如果定义不对,组件运行会报错
VUE通过定义组件的方式来对特定功能进行封装,将功能模块化,非常方便,用起来也非常方便,不过一定学懂了才能灵活运用
先来看下效果
定义一个组件TestCheckboGroup
<template>
<div>
<el-checkbox-group v-model="selectValue" >
<div v-for="item in options" :key="item.value">
<el-checkbox :label="item.label" >{{item.label}} </el-checkbox>
</div>
</el-checkbox-group>
</div>
</template>
<script>
export default {
name: 'TestCheckboxGroup',
componentName: 'TestCheckboxGroup',
data() {
// value:{}
return {
selectValue: this.value,
}
},
props: {
//value: {},
value: {
type: [String, Object, Array],
default: [] //
//default: "1" 出错
//default: "" 出错
//type:Number,
// default:1
},
disabled: Boolean,
min: Number,
max: Number,
size: String,
fill: String,
textColor: String,
/*新定义的options属性*/
options: {
type: Array,
default: function() {
return []
},
required: true
/*required: false*/
},
}
,
watch: {
selectValue(val) {
//注释 赋不了值 ,不注释死循环
this.$emit('input', val)
// value=val;
console.log("selectValue")
console.log("selectValue")
console.log(JSON.stringify(val))
},
value(val) {
//为什么 imageSelect 不出错?????
//取消这里正确了
//this.selectValue = val
},
}
};
</script>
调用
<template>
<div id="testslot" style="margin:100px">
<TestCheckboxGroup v-model="mycheck" :options="options">
</TestCheckboxGroup>
{{mycheck}}
<br/>
<el-button @click="handleTest()">
console打印测试
</el-button>
</div>
</template>
<script>
import TestCheckboxGroup from './TestCheckBoxGroup'
export default {
name: "testGroup",
components: {
TestCheckboxGroup
},
data() {
return {
//mycheck: '',//不能赋值 为'' ,否刚这个会变为布尔值了
//mycheck:undefined,//测试验证是正确的
mycheck:[],//测试验证是正确的
mycheck1: {
type: [String, Object, Array],
//default: [] // 出错
default: "" // 出错
},
options: [
{
label: "项目1",
value: "AAA",
},
{
label: "项目2",
value: "BBB",
},{
label: "项目3",
value: "CCC",
},
]
};
},
methods: {
handleTest(){
console.log("取得多选框组的值");
console.log(JSON.stringify(this.mycheck) );
alert(JSON.stringify(this.mycheck) );
}
},
};
</script>
测试验证