父子组件传值
# 父子组件传值
- 父传子
/**
父组件
*/
<template>
<div class="wrapper">
<div>
first: <childrenVue :name="reactiveName.name"/>
</div>
</div>
</template>
<script lang="ts" setup>
import { reactive } from "vue"
let reactiveName = reactive({
name: ""
})
</script>
/***********************分割线*******************/
/**
子组件
*/
<template>
<div class="wrapper">
<!-- 在模板中可以直接使用 -->
<div>
{{name}}
</div>
</div>
</template>
<script lang="ts" setup>
// 第一种方式
defineProps({
name: {
type: String,
default: "zhangsan"
}
})
// 第二种方式
interface PropTypes{
name: string
}
defineProps<PropTypes>()
// 如果需要使用结合ts设置props的默认的话,那就要结合
/**
withDefaults(defineProps<PropTypes>(), {
name: "zhangsan"
})
*/
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
- 子传父
/** 子组件 */
<script lang="ts" setup>
import { reactive } from "vue"
let reactiveType = reactive({
name: ""
})
// 不使用ts
const emits = defineEmits(["change"])
const changeValue = ()=>{
emits("change", reactiveType.name);
}
// 使用ts
const emits2 = defineEmits<{
(e: "changeName", name: string): void;
}>()
const changeValue = ()=>{
emits2("changeName", "changeValue");
}
</script>
/***********************分割线*******************/
/** 父组件 */
<template>
<div class="wrapper">
<div>
first: <childrenVue @change="getValue" @changeName="getChangeName" :name="reactiveName.name"/>
</div>
</div>
</template>
<script lang="ts" setup>
import { reactive } from "vue"
const getValue = (value: string)=>{
console.log(value)
}
const getChangeName = (value: string)=>{
console.log(value)
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
- 子组件暴露内部方法给父组件使用
/** 子组件 **/
<script lang="ts" setup>
interface Expose{
name: string;
}
defineExpose<Expose>({
name: "zhansan"
})
</script>
/***********************分割线*******************/
/** 父组件 */
<template>
<div class="wrapper">
<div>
first: <childrenVue ref="childrenRef" />
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue"
import childrenVue from "@/**/index.vue"
const childrenRef = ref<InstanceType<typeof childrenVue>>();
childrenRef.value?.name
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
编辑 (opens new window)
上次更新: 2023/05/17, 21:35:56