热搜:m1 nginx 代理 前端

再谈:v-model语法糖组件通信

2024-03-17 19:20:34

vue2

  • vue2 中父子组件数据同步 父→子 子→父 如何实现?

    • v-model="count" 或者 xxx.sync="msg"

  • v-model 语法糖 完整写法?

    • :value="count" 和 @input="count=$event"

  • xxx.sync 语法糖 完整写法?

    • :xxx="msg" 和 @update:xxx="msg=$event"

vue3

  • vue3 中 v-model 语法糖?

    • :modelValue="count" 和 @update:modelValue="count=$event"

  • vue3 中 v-model:xxx 语法糖?

    • :xxx="count" 和 @update:xxx="count=$event"

vue2举例

在 Vue 2 中,v-model 的使用实际上是语法糖,其背后其实是一个包含 :value 和 @input 的绑定。当我们在父子组件中传参并希望实现双向数据绑定时,我们可以用 v-model 结合自定义事件来实现。下面是一个父子组件传参的例子:

假设我们有一个子组件,它包含一个输入框:

// 子组件 ChildComponent.vue

<template>
  <div>
    <input type="text" :value="value" @input="updateValue" /> 
  </div>
</template>

<script>
export default {
  props: ['value'],
  methods: {
    updateValue(event) {
      this.$emit('input', event.target.value);
    }
  }
}
</script>

子组件接收一个 value props。当用户在输入框中输入时,它会发出一个 input 事件并传送新的值。

现在,我们在父组件中使用 v-model 来接收和传递这个值:

// 父组件 ParentComponent.vue
<template>
  <div>
    <ChildComponent v-model="parentValue" />
  </div>
</template>

<script>`
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentValue: ''
    }
  }
}
</script>

父组件现在使用 v-model 将 parentValue 绑定到子组件上。当输入框的值在子组件中改变时,这个变化会因为子组件的 $emit 而反映在父组件的 parentValue 上,实现了双向数据的绑定。

vue3举例

子组件

<script setup lang="ts">
defineProps<{
modelValue: number
}>()
const emit = defineEmits<{
(e: 'update:modelValue', count: number): void
}>()
</script>

<template>
<div class="-page" @click="emit('update:modelValue', modelValue + 1)">
子组件{{ modelValue }}
</div>
</template>

<style lang="scss" scoped></style>

父组件

<script setup lang="ts">

import { ref } from 'vue'
const count1 = ref(0)
</script>
<template>
    <son v-model="count1" />
</template>