自定义组件实现v-model————vue2

  • 要使自定义的Vue组件支持v-model,需要实现一个名为value的prop和一个名为input的事件。
  • 在组件内部,将value prop 绑定到组件的内部状态,然后在对内部状态进行修改时触发input事件。

自定义UI组件

<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>


使用组件

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

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

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

};
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43848576/article/details/134117304
今日推荐