Vue2和Vue3中的v-model

467 阅读1分钟

Vue3中新语法

v-model

update:modelValue 是默认的, vue3 使用特定的 modelValue ,避免 value 的占用;

废除了 model 组件选项, 统一了.sync

// 父组件
<van-action-sheet
    v-model="myTitle"
    v-model:show="showStatus"
    v-model:name="myName"
    close-on-click-action
    :actions="statusActions"
  />

// 子组件
export default defineComponent({
	props: {
                  show: {type: String},
                  name: {type: String},
                  modelValue: {type: String} // 默认的v-model
	},
	emits: ['select', 'cancel', 'update:modelValue', 'update:show', 'update:name'],
	
        setup(props, {slots, emit}){
	   const updateShow = (show: boolean) => emit('update:show', show);
            const updateName = (_name) => emit('update:name', _name);
	},
        
        computed:{
              newName:{
               get:function(){
                return this.name
               },
              set:function(value){
                this.$emit('update:name',value)
               }
             },
             newAge:{
              get:function(){
               return this.age
              },
              set:function(value){
               this.$emit('update:age',value)
              }
              },
     }
});

Vue2中的v-model 与 .sync

<child-comp v-model="msg" :foo.sync="foo"  />
  
//可翻译为
<child-comp 
 :value="msg" @input="msg=$event"   
 :foo="foo" @update:foo="foo=$event"  />


// 子组件
export default {
    props:{
          value:{
           type:String,
           default:''
          },
          foo:{
           type:String,
           default:""
          }
	},
computed: {
	newValue:{
	   get:function(){
	    return this.value
	   },
	   set:function(value){
	    this.$emit('input',value)
	   }
	 },
        newFoo:{
          get:function(){
           return this.foo
          },
          set:function(value){
           this.$emit('update:foo',value);
          }
         },
 }
}