父子嵌套关系的 双向绑定
简而言之 在父组件改变值 会响应到子组件 在子组件中改变 也会响应到父组件中
v-model ‘解体’
v-model 的双向绑定功能 可以用 value 和 @input 来模拟
演示v-model 的解体功能
父组件
引入子组件 在子组件上利用双向绑定 这里的v-model 可以理解为 :value =“an” @input="$emit.target.value"
<template>
<div>
<son-zi v-model="an"></son-zi>
</div>
</template>
<script>
import sonZi from './son.vue'
export default {
data() {
return {
an: 1000
}
},
components: {
sonZi
}
}
</script>
<style lang="less" scoped>
</style>
子组件
接受 父组件传递过来的值 并且再传递过去 ,这样即使在 子组件中改变这个值 父组件也会响应
<template>
<div>
<v-input :value="value" @input="$emit.target.value">
</v-input>
</div>
</template>
<script>
export default {
props: ['value']
}
</script>
<style lang="less" scoped>
</style>
下面 用vue 中 vant的弹框组件来掩饰
需求 点击按钮 显示弹框 但是弹框插件时独立的。 点击按钮 按钮给弹框传值 再点击 旁边 弹框按钮 又会 使 value 变为 false 返回 值给 按钮组件 使按钮组件的 an 变为false
弹框插件
<template>
<!-- 不感兴趣组件 -->
<van-dialog
:value="value"
@input="$emit('input')"
:show-confirm-button="false"
close-on-click-overlay
show-cancel-button>
</van-dialog>
<!-- 这里面 :value 和 @input 是 v-model的解体 -->
<!-- : value 是传递过来的值 而 @input 是向父级响应的值 -->
<!-- :show-confirm-button="false" // 不显示 “确定” 按钮 -->
<!-- close-on-click-overlay // 点击旁处关闭对话框 -->
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default: false // 默认值
}
}
}
</script>
<style lang="less" scoped>
</style>
按钮组件
<template>
<dis-like v-model="an"></dis-like>
</template>
<script>
import disLike from './dislike.vue'
export default {
data () {
return {
an: false
}
},
components: {
disLike
},
}
</script>
<style lang="less" scoped>
</style>