自定义组件上使用v-model监听
父组件
<template>
<search v-model="keywords" placeholder="请输入查询内容"></search>
</template>
<script>
import search from './search.vue'
export default {
components: {
search
},
data() {
return {
keywords: ''
}
},
watch: {
keywords(val) {
console.log(val, 'v-model监听的值')
}
}
}
</script>
子组件
// search.vue
<template>
<div class="search-box">
<div class="search-content">
<span class="icon-search"></span>
<input type="text" v-model="currentValue" :placeholder="placeholder" :autofocus="autofocus" @click="isShow = true" @blur="outBlur">
<a href="javascript:;" @click="isShow = false, currentValue = ''" v-show="isShow">取消</a>
</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
},
placeholder: {
type: String,
default: '请输入'
},
autofocus: {
type: Boolean,
default: false
}
},
data() {
return{
currentValue: this.value,
isShow: this.value ? true : false
}
},
watch: {
currentValue(val) {
this.$emit('input', val)
this.isShow = val
},
value(val) {
this.currentValue = val
}
},
methods: {
outBlur() {
if (!this.currentValue) {
this.isShow = false
}
}
}
}
</script>
Last updated