一般来说,子组件不应该直接修改父组件的 props,因为这会违背 Vue 的单向数据流原则。
使用 ref 和 toRefs 修改父组件的值
子组件
props = defineProps({searchParams: {type: Object,required: true}
})const { searchParams } = toRefs(props);searchParams.value=xxx就可以直接修改父组件的值const aaa = computed(() => {return props.searchParams
})
//这个是为了保证父组件的searchParams改变了后
//子组件能响应式接收到
此时,searchParams.value与props.searchParams是一样的引用,子组件可以直接修改 searchParams.value,修改会同步到父组件。
aaa =props.searchParams不可行的原因
//1、Vue 中的 props 是只读的,不能修改
//2、aaa中存放的只是props.searchParams的初始值,props.searchParams变化了,并不会通知aaa
子组件通过事件通知
在这种方式中,子组件通过 $emit 将数据的更新请求传递给父组件,父组件接收到事件后更新自己的状态。这是 Vue 中推荐的做法。
父组件
<child @update="updateParams">updateParams(newParams){this.params = newParams
}
子组件
this.$emit("update",this.localParams)
v-model 双向绑定(父组件控制数据,子组件自动更新)【没看懂,最繁琐的一种方式】
父组件
<template><ChildComponent v-model="searchParams" />
</template><script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';// 父组件的数据 searchParams
const searchParams = ref({ term: '' });
</script>
子组件
<template><!-- 简化为直接使用 localModel 进行 v-model 绑定 --><el-input v-model="localModel.term" placeholder="请输入内容" />
</template><script setup lang="ts">
import { computed } from 'vue';
import { defineProps, defineEmits } from 'vue';// 接收父组件传递的 modelValue 作为 props
const props = defineProps({modelValue: {type: Object,required: true}
});// 定义 emits 用于传递更新给父组件
const emit = defineEmits(['update:modelValue']);// 使用 computed 创建双向绑定的属性
const localModel = computed({get() {return props.modelValue; // 获取父组件传递的数据},set(value) {emit('update:modelValue', value); // 当 localModel 改变时,向父组件发送更新}
});
</script>