1.前言:
上一篇我们讲到了v-model的组件双向数据绑定,他有一个缺点就是无法自定义绑定的属性。
比如:input 输入框他的属性就是 value,复选框就是 checked,但是我们有时候想修改一下属性该怎么办呢?
答案:使用 ‘.sync’ 修饰符,那么我们接下来看一下具体用法
2.父组件
<template>
<div>
<div class="main">
我是 father 组件
展示price变化状态:{{price}}
<son :value1.sync="price"></son>
//注意:我们这里使用.sync 改变了 input输入框 默认的 :value 属性
</div>
</div>
</template>
<script>
import son from "@/components/sonCom.vue";
export default {
name: "fatherCom",
components: {
son,
},
data() {
return {
price: '100gbfg',
}
},
updated(){
console.log(this.price)
}
}
</script>
3.子组件
<template>
<div class="box">
<p class="title">我是son组件</p>
<div class="twoModel">
<div style="border: 1px solid #000">
<p> .sync 双向绑定</p>
<input :value="value1" @input="dateValue($event.target.value)">
</div>
</div>
</div>
</template>
<script>
export default {
name: "sonCom",
props:{
// .sync 双向绑定练习
value1:{
type: String,
default: ''
}
},
methods: {
dateValue(val) {
//注意:当我们使用 .sync 修饰符后,$emit 中的事件名改为 “update:属性名”
this.$emit('update:value1', val)
}
}
}
</script>