vue3组件传值v-model的双向数据绑定

组件v-model

父组件内

const selectParams = ref({
  name: null,
  address: null,
  desc: null
})

我们在子组件上定义v-model用于双向绑值,父组件内需要定义一个绑定的变量searchForm

子组件
然后在子组件内通过defineProps接收父组件绑定的值

const props = defineProps({
  modelValue: {
    type: Function,
    default: () => ({
      name: null,
      address: null,
      desc: null
    }),
  },
});

const { modelValue } = toRefs(props);

通过toRefs解构defineProps内的modelValue,这样子组件的表单就可以直接使用modelValue
子组件内点击搜索按钮,此时通过update:modelValue事件回传改值

const emit = defineEmits(["update:modelValue", "onSearch"]);
const onSearch = () => {
  // 子组件直接修改modelValue的值,update:modelValue表示修改modelValue,修改为第二个参数的值
  emit("update:modelValue", modelValue.value);
  // 搜索时返回一个事件,父组件内执行查询列表
  emit("onSearch");
};

父组件

const onSearch = () => {
  console.log("查询列表", searchForm.value);
};

通过给组件绑定v-model让父子组件的数据双向互通,父组件可以拿到最新的值。

分页组件的封装

这里举例一个分页组件的封装,通过v-model双向绑定,数据修改后通知父组件更新

// 父组件


const pageInfo = ref({
  num: 1,
  size: 12,
  total: 50
});

const onPageChange = () => {
  console.log('分页变化', pageInfo.value);
};
// 子组件


image.png
另外,你也可以通过withDefaultsdefineProps标注数据类型,结果是一样的

interface IProps {
  modelValue: {
    num: number;
    size: number;
    total: number;
  };
}

const props = withDefaults(defineProps(), {
  modelValue: () => ({
    num: 1,
    size: 12,
    total: 0
  })
});
const { modelValue } = toRefs(props);

你可能感兴趣的:(vue3组件传值v-model的双向数据绑定)