Custom component implements v-model————vue2

  • To make a custom Vue component support v-model, you need to implement a prop named value and an event named input.
  • Inside the component, bind the value prop to the component's internal state, and then fire the input event when the internal state is modified.

Custom UI components

<template> 
  <input :value="value" @input="change" />
</template>

<script>
export default {
    
    
  name: 'MyInput',
  props: {
    
    
    value: String
  },
  methods:{
    
    
  	change(e){
    
    
		this.$emit('input', e.target.value)
	}
 }
};
</script>


Use components

<template>
  <div>
    <my-input v-model="message" /> 
  </div>
</template>

<script>
import MyInput from './MyInput.vue';

export default {
    
    
  components: {
    
    
    MyInput
  },
  data() {
    
    
    return {
    
    
      message: ''
    };
  },

};
</script>

Guess you like

Origin blog.csdn.net/weixin_43848576/article/details/134117304