0
点赞
收藏
分享

微信扫一扫

vue3:自定义组件使用v-model

kiliwalk 5小时前 阅读 0

首先,在自定义组件里,得有一个名为modelValue的属性,当modelValue变化的时候,触发update:modelValue事件,把新值传给父组件。

子组件:

选项式API写法

<template>
  <div style="width: 100%">
    <t-form labelWidth="70px">
    <t-form-item label="标题">
          <t-input size="small" v-model="modelValue.text" :maxcharacter="52" />
        </t-form-item>
        <t-form-item label="字体">
          <e-font v-model="modelValue.textStyle"/>
        </t-form-item>
        <t-form-item label="位置(X)">
          <e-chart-position v-model="modelValue.left" :direction="'x'" />
        </t-form-item>
        <t-form-item label="位置(Y)">
          <e-chart-position v-model="modelValue.top" :direction="'y'" />
        </t-form-item>
      </t-form>
  </div>
</template>

<script>
import EChartPosition from "@/components/designer/e-chart-position";
export default {
  name:'chart-title',
  components: { EChartPosition },
  props: {
    modelValue: {
      type: Object,
      required: false
    }
  },
  watch:{
    modelValue(newVal){
      this.$emit('update:modelValue', newVal); // 通知父组件更新 modelValue 的值
    }
  }
}
</script>

<style scoped>
</style>

组合式API写法,modelValue前面要加props

<template>
  <div style="width: 100%">
    <t-form labelWidth="70px">
    <t-form-item label="标题">
          <t-input size="small" v-model="props.modelValue.text" :maxcharacter="52" />
        </t-form-item>
        <t-form-item label="字体">
          <e-font v-model="props.modelValue.textStyle"/>
        </t-form-item>
        <t-form-item label="位置(X)">
          <e-chart-position v-model="props.modelValue.left" :direction="'x'" />
        </t-form-item>
        <t-form-item label="位置(Y)">
          <e-chart-position v-model="props.modelValue.top" :direction="'y'" />
        </t-form-item>
      </t-form>
  </div>
</template>

<script setup>
import { watch } from 'vue'
import EChartPosition from "@/components/designer/e-chart-position";
const props = defineProps({
  modelValue: { type: Object, required: false }
})
const emit = defineEmits(['update:modelValue'])
watch(()=>props.modelValue,(newVal)=>{
		emit('update:modelValue', newVal)
	})
</script>

<style scoped>
</style>

父组件调用子组件,特别注意,这里不需要@update之类的了。

<chart-title v-model="attribute.title" />

当然,可能自定义组件要传给父组件的值,不像我案例里这么简单,需要经过很多处理过程,只需要将处理后的数据用触发update:modelValue自定义事件的方法传过去就可以了,如下:

const updateValue = () => {
  emit('update:modelValue', colorList)
}
举报

相关推荐

0 条评论