Vue组件上使用v-model双向绑定

首先要明确它就是个语法糖 (v-model 相当于 onChange 的语法糖)
<input type="text" :value= 'name' @input='name = $event.target.value'>

 <p>{{name}}</p>

上面这个功能和v-model是一致的
你自己也可以用@input监控输入的结果 就可以找到target下面的value
下面有一个场景
要实现一个搜索模糊匹配功能,考虑到组件的复用,就单独把搜索框抽出来作为一个子组件。在以往的开发中,
一般会在input框中的值变化时向父组件emit一个事件,并带上一些父组件中需要的参数(比如搜索的关键词,或者搜索之后返回的结果)

大概的实现方式如下:

 父组件
<template>
    <div>
        <search v-model="keywords"></search>
        <button @click="submit">提交</button>
    </div>
</template>
<script>
import search from '@/components/index/search.vue'
export default {
    data() {
        return {
            keywords: ''
        }
    },
    components: {
        search
    },
    methods: {
        submit() {
            console.log('keywords:', this.keywords)
        }
    }
}
</script>

子组件
<template>
    <div>
        <input :value="value" @input="$emit('input', $event.target.value)" type="text" name="keywords">
    </div>
</template>
<script>
export default {
    props: ['value']
}
</script>
posted @ 2020-02-19 11:48  Model-Zachary  阅读(139)  评论(0编辑  收藏  举报