一.Props
// 父组件
<div>
<children :flag="state.eflag" />
</div>
<script setup>
import children from './children.vue'
import { reactive } from 'vue'
const state = reactive({
eflag: true,
})
</script>
// 子组件
<div>
<div>{{ flag }}</div>
</div>
<script setup>
const prop = defineProps({
flag: {
type: Boolean, // Object , Array , Function , Number
default: false
}
})
</script>
二.emit
// 子组件
<template>
<div >
<el-button type="primary" @click="handleEdit(item)">
点我
</el-button>
</div>
</template>
<script setup>
// handleEdit子组件方法, selfDataEdit父组件方法
const emit = defineEmits([
'selfDataEdit',
])
const handleEdit = (row) => {
emit('selfDataEdit', row)
}
defineExpose({
handleEdit,
})
</script>
// 父组件
<template>
<div>
<Table @selfDataEdit="handleEdit"></Table>
</div>
</template>
<script setup>
import Table from '@/components/common/Table/index.vue'
const handleEdit = (value) => {
// 要执行的方法
}
</script>
三.v-model
// 父组件
<template>
<child-components v-model:num="state.num"></child-components>
</template>
<script setup>
import { reactive } from 'vue'
import ChildComponents from './child.vue'
const state = reactive({
num: 721
})
</script>
//子组件
<template>
<div>
<button @click="handleAdd" type="button">添加</button>
</div>
</template>
<script setup>
import { defineEmits, defineProps } from 'vue'
const props = defineProps({
num: {
type: Number,
default: 0,
},
})
const emits = defineEmits(['update:list'])
const handleAdd = (val) => {
emits('update:num', val) //update:固定写法
}
</script>
四.ref
// 父组件
<template>
<son ref="childMap" @click="showCont" />
</template>
<script setup>
const childMap = ref(null);
const showCont = () => {
childMap.value.state.num; // 调用子组件的参数
childMap.value.clearMap("gczLayer"); // 调用子组件的方法
}
<script>
// 子组件
<template></template>
<script setup>
import { reactive } from "vue";
const state = reactive({
num: 3
})
const clearMap = (val) => {
console.log('这是子组件', val)
}
defineExpose(
state,
clearMap
)
<script>
五. provide/inject
如果父组件使用readonly 这么设置 provide('numVal', readonly (num)),那么子孙及组件不可更改该值
//父组件
<template>
<div>
<p>父:{{ num }}</p>
<button @click="dianwo">父级点击</button>
<left></left>
</div>
</template>
<script setup>
import { ref, provide } from "vue";
import left from "./left.vue";
const num = ref(0)
provide('numVal', num)
const dianwo = () => {
num.value = 1
};
</script>
//子组件
<template>
<!-- <p>子:{{num}}</p> -->
<!-- <button @click="dianwo">子级点击</button> -->
<components></components>
</template>
<script setup>
import { ref, reactive, inject } from "vue";
import components from "./virtually/components.vue";
// let num = inject('numVal')
const dianwo = () => {
console.log('asd', num)
num.value = 2
}
</script>
//孙子组件
<template>
<p>孙子:{{num}}</p>
<button @click="dianwo">孙子级点击</button>
</template>
<script setup>
import { ref, reactive, inject } from "vue";
let num = inject('numVal')
const dianwo = () => {
console.log('asd', num)
num.value = 3
}
</script>
六.其余
当然还有 pinia 本地存储 混入之类的传值,跟vue2差不多,就不一一解释了