Vue3 Setup语法糖,父子组件之间传各种数据类型方法
一、父组件向子组件使用语法糖传字符串类型
1.父组件
msg是你的自定义的变量名,用于传给子组件,content是你父组件的要传给子组件的数据。
<template>
<div>
<Hello :msg="content" />
</div>
</template>
<script setup>
import { ref } from "vue";
import Hello from "../components/HelloWorld.vue";
const content = ref("那就这样吧");
</script>
2.子组件
语法糖中可以直接在props = defineProps()的方法里面写你穿过来的数据,最后在模板中调用就ok了
<template>
<div>
<h1>{{ props.msg }}</h1>
</div>
</template>
<script setup>
const props = defineProps({
msg: String,
});
</script>
最终呈现处这样的效果
二、父组件向子组件使用语法糖传数组类型
1.父组件传递
组件中DateList是你声明传递给子组件的名称,ArrayList是你要传递给子组件的数据。
<template>
<div>
<Hello :DateList="ArrayList" />
</div>
</template>
<script setup>
import { reactive } from "vue";
import Hello from "../components/HelloWorld.vue";
const ArrayList = reactive([
{
id: 1,
name: "法外",
},
{
id: 2,
name: "狂徒",
},
{
id: 3,
name: "张三",
},
]);
</script>
2.子组件接收
语法糖中可以直接在props = defineProps()的方法里面写你穿过来的数据,最后在模板中循环输出就ok了
<template>
<div>
<h1>{{ props.msg }}</h1>
<div v-for="(item, index) in props.DateList" :key="item.id">
{{ item.name }}
</div>
</div>
</template>
<script setup>
const props = defineProps({
msg: String,
DateList: Array,
});
console.log(props.DateList);
</script>
呈现效果
三.子组件向父组件使用语法糖传字值
1.子组件
子传父需要用到事件来传递, let emigFun = defineEmits(["handLer"]); 使用defineEmits语法糖,创建一个自定义事件,然后根据自定义事件来传递你想要传递的类型(如下图)
<template>
<div>
<div @click="fun">
子传父
</div>
</div>
</template>
<script setup>
import { reactive } from "vue";
let emigFun = defineEmits(["handLer"]);//使用defineEmits语法糖的方法来创建自定义事件。
const dat = reactive([
{
name: 123,
id: 1,
},
{
name: 123,
id: 1,
},
{
name: 123,
id: 1,
},
{
name: 123,
id: 1,
},
]);
const fun = () => {
emigFun("handLer", dat);//左边是你的自定义事件名,右边是你要传的数据。
};
</script>
2.父组件
父组件这边就可以直接使用你子组件创建的自定义事件,加上你父组件的事件名,通过形参的方式成功拿到子组件的数据(如下图)
<template>
<div>
<Hello @handLer="hand" />
<div>
点击拿到子组件的值
</div>
</div>
</template>
<script setup>
import Hello from "../components/HelloWorld.vue";
const hand = (v) => {
console.log(v);
};
</script>
效果展示
总结
另外还有一些使用setup语法糖的一些问题,下一篇给大家讲一下,其次Vue父子组件互相传值,传来传去新手容易懵,多理清思路,慢慢来,还有什么更好的见解,或者想法请在下方评论探讨。