平时我们在使用输入类型标签的时候由于某些功能为了方便经常会封装成组件来使用,但是由于平时我们都是通过:绑定值父组件可以同步传值给子组件,但是子组件传父组件却要通过触发$emit()事件来传值,在父组件还需要使用自定义事件来绑定值,很不方便,所以我们可以使用下面两种方法来实现
此处以我今天使用到的组件为例示范,封装一个步进,由于iview里面的步进器不是我想要的效果,所以这里我们对iview的Input组件通过原来的插槽进行二次封装
父组件(使用组件):
<template>
<div>
<CustomInputNumber v-model="value1"></CustomInputNumber>
<span>{{value1}}</span>
<CustomInputNumberTwo :value.sync="value2"></CustomInputNumberTwo>
<span>{{value2}}</span>
</div>
</template>
<script>
import CustomInputNumber from "../../components/custom-input-number/custom-input-number.vue";
import CustomInputNumberTwo from "../../components/custom-input-number-two/custom-input-number.vue";
export default {
name: "",
components: {
CustomInputNumber,
CustomInputNumberTwo,
},
data() {
return {
value1:0,
value2:0
};
},
};
</script>
<style scoped>
</style>
方法一:通过配置model属性
model:{}可以配置prop(外部传过来的参数,如果是外部传进来的input组件就不要用v-model绑定了直接写:value)跟event(触发事件)事件,这里事件名可以自己随便写,然后我们就可以在父组件通过v-model实时拿到输入框里面的值并绑定到我们对应的父组件中去
子组件实例一
<template>
<div>
<Input :value="value" style="width: 120px" type="number" class="custom-input-number">
<Button slot="prepend" icon="ios-add" @click="add"></Button>
<Button
slot="append"
icon="ios-remove"
@click="sub"
:disabled="isDisable"
></Button>
</Input>
</div>
</template>
<script>
export default {
name: "",
model: {
event: "update",
prop:'value'
},
props:{
value:String
},
data() {
return {
isDisable: false,
};
},
watch: {
value: {
immediate:true,//立即监听
handler(newValue) {
if (newValue < 1) {
this.isDisable = true;
} else {
this.isDisable = false;
}
this.$emit("update", this.value);//由于输入框内的值可以通过点击按钮改变,所以不能直接通过on-change事件触发emit 而是通过监听来触发保证父组件随时都能收到值
},
},
},
methods: {
add() {
this.value++;
},
sub() {
this.value--;
},
},
};
</script>
<style lang="less" scoped>
.custom-input-number {
/deep/ .ivu-input {
text-align: center;
}
}
</style>
方法二:通过:事件.sync,如:change.sync="form.value"
子组件实例二
<template>
<div>
<Input :value="value" style="width: 120px" type="number" class="custom-input-number">
<Button slot="prepend" icon="ios-add" @click="add"></Button>
<Button
slot="append"
icon="ios-remove"
@click="sub"
:disabled="isDisable"
></Button>
</Input>
</div>
</template>
<script>
export default {
name: "",
props:{
value:String
},
data() {
return {
isDisable: false,
};
},
watch: {
value: {
immediate:true,//立即监听
handler(newValue) {
if (newValue < 1) {
this.isDisable = true;
} else {
this.isDisable = false;
}
this.$emit("update:value", newValue);
},
},
},
methods: {
add() {
this.value++;
},
sub() {
this.value--;
},
},
};
</script>
<style lang="less" scoped>
.custom-input-number {
/deep/ .ivu-input {
text-align: center;
}
}
</style>
效果:步进器下面的数值是根据组件同步变化的