首页 vue自定义v-model
文章
取消

vue自定义v-model

自定义v-model

  • input输入框自定义v-model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Input.vue

<template>
    <input type="text" :value="modelValue" @input="change1">
</template>

<script setup>
    defineProps(['modelValue'])
    const emit = defineEmits(['update:modelValue'])
    function change1(e) {
        emit('update:modelValue', e.target.value)
    }
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup>
    import Input from './children/Input.vue'
    import {ref} from "vue"
    const inputData = ref('内容')
</script>

<template>
    <div>
        
        <Input v-model="inputData" />
    </div>
</template>

示例如下:

v-model示例



  • 选择按钮自定v-model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 单文件组件:OptionComponents.vue 

<template>
    <input
      type="checkbox"
      :checked="checked"
      @change="$emit('change', $event.target.checked)"
    />
  </template>
  
  <script>
  export default {
    model: {
      prop: 'checked',
      event: 'change'
    },
    props: {
      checked: Boolean
    }
  };
  </script>
  
  <style scoped>
  /* 可以添加一些样式,如果需要的话 */
  </style>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script setup>
    import Input from './children/Input.vue'
    import OptionComponents from './children/OptionComponents.vue';
    import {ref} from "vue"
    const inputData = ref('内容')
    const isChecked = ref(true)
</script>

<template>
    <div>
        <OptionComponents v-model:checked="isChecked" />
        <hr>
        
        <Input v-model="inputData" />
    </div>
</template>

示例如下:

转摘分享请注明出处

JavaScript作用域

JavaScript设计模式