美文网首页
Vue 自定义组件的 v-model

Vue 自定义组件的 v-model

作者: 时光经年 | 来源:发表于2018-12-19 16:05 被阅读0次

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会有所不同。model这个参数选项可以修改默认参数。

(备注方便自己后面查文档)

 <div id='app'>
    <div>v-modle 在自定义组件上面的应用</div> 
    <base-checkbox v-model="lovingVue"></base-checkbox>
    <base-input v-model="inputValue"></base-input>
    <div>{{inputValue}}</div>
 </div>



<script type="text/javascript">
    Vue.component('base-checkbox', {
      model: {
        prop: 'checked',
        event: 'change'
      },
      props: {
        checked: Boolean
      },
      template: `
        <div>
        <input
          type="checkbox"
          v-bind:checked="checked"
          v-on:change="$emit('change', $event.target.checked)"
        > 
        </div> 
      `
    })

    Vue.component('base-input', {
      props: ['value'],
      template: `
        <div>
        <input
          type="text"
          v-bind:value="value"
          v-on:input="$emit('input', $event.target.value)"
        > 
        </div> 
      `
    })

    new Vue({
        el:'#app',
        data:{
            lovingVue:true,
            inputValue:'这是input'
        }
    })
</script>

相关文章

网友评论

      本文标题:Vue 自定义组件的 v-model

      本文链接:https://www.haomeiwen.com/subject/lhvjkqtx.html