练习 Vue 自定义事件 v-model ,代码如下:

<template>
    <div>
      <base-checkbox v-model="lovingVue"></base-checkbox>
    </div>
</template>

<script>
import Vue from 'vue'
export default{
  data() {
    return {
      checked: false
    }
  }
}
Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})
</script>

 

报错提示:the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

修改后代码:

<template>
    <div>
      <base-checkbox v-model="lovingVue"></base-checkbox>
      <span>{{lovingVue}}</span>
    </div>
</template>

<script>
import Vue from 'vue'
export default{
  data () {
    return {
      checked: false,
      lovingVue: ''
    }
  }
}
Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})
</script>

 

Logo

前往低代码交流专区

更多推荐