当前位置:网站首页>Analysis of the principle of V-model and its application in user defined components

Analysis of the principle of V-model and its application in user defined components

2022-06-13 04:42:00 Dax1_

v-model Two-way binding of

v-model yes v-bind and v-on Grammar sugar used together

<input v-model="value" />

//  Is equivalent to : 
<input :value="value" @input="value= $event.target.value" />

v-model Use in custom components

In order for our components to support v-model Two way binding , The component needs to accept a props And send out a input event .

//  Parent component 

<template>
  <div>
    <Dialog :visible="x" @update:visible="x = $event"></Dialog>
    <!-- Equivalent to -->
    <Dialog v-model:visible="x"></Dialog>
  </div>
</template>
//  Child components  Dialog

<script lang="ts">
export default {
    
  props: {
    
    visible: {
    
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    
    const close = () => {
    
      context.emit('update:visible', true)
    }
    return {
    close}
  }
};
</script>

Use... In custom components v-model, take visible Pass the value of to the subcomponent , Subcomponent receive prop(visible), meanwhile , Using update:visivle event ( In general use input event , This is a personal habit ) Will be worth passing $emit, Pass the value back to the parent component , Directly assign to visible, This forms a two-way data binding for custom components .

原网站

版权声明
本文为[Dax1_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280521342781.html