记录vue3中两种setup的传值方法。
setup函数:
父传子:
父组件 :在引入的子组件上绑定下图data属性,值为msg1(属性命名随意,但是要与子组件内接收的保持一致),msg1为所需要传给子组件的值。
子组件 :props接收父组件传的值,与父组件内绑定的属性名一致。在setup函数中,携带第一个参数props,这里面的props即为父组件传来的内容,可以console.log(props)看内容,return出去即可直接使用。
<!-- setup函数 父传子 -->
<!-- 父组件 -->
<template>
<div>
<div>
<Testview :data="msg1" />
</div>
</div>
</template>
<script>
import { ref } from "vue";
import Testview from "../components/TestView.vue";
export default {
components: {
Testview,
},
setup() {
const msg1 = ref("setup------函数");
return {
msg1
};
},
};
</script>
<!-- 子组件 -->
<template>
<h1>{{ props.data }}</h1>
</template>
<script>
export default {
props: {
data: String,
},
setup(props) {
return { props };
},
};
</script>
子传父:
父组件 :在引入的子组件上绑定 msg事件,内容为value函数(‘msg’的命名随意,但要与子组件mits内的一致),在value函数中的形参即为子组件传入的值。
子组件 :绑定一个方法(btn)点击执行传参。在setup函数中,需要使用第二个参数 context,调用context.emit传递参数,第一个参数为父组件内绑定的事件名,第二个参数为需要传过去的数据。在setup函数外要把传递的事件名写在 emits中,否则会报警告。
注:
setup函数中的两个参数,命名可以随意,但第一个表示接收,第二个表示传递。也就是只用于子传父时,也要把第一个参数带上,否则会报错。
<!-- setup函数 子传父 -->
<!-- 父组件 -->
<template>
<div>
<div>
<h1>{{ chuan }}</h1>
<Testview @msg="value" />
</div>
</div>
</template>
<script>
import { ref } from "vue";
import Testview from "../components/TestView.vue";
export default {
components: {
Testview,
},
setup() {
const chuan = ref("");
const value = (val) => {
chuan.value = val;
};
return {
chuan,
value,
};
},
};
</script>
<!-- 子组件 -->
<template>
<button @click="btn()">点击</button>
</template>
<script>
import { ref } from "vue";
export default {
emits: ["msg"],
setup(props, context) {
let num = ref(666);
const btn = () => {
context.emit("msg", num.value);
};
return { props, num, btn };
},
};
</script>
setup语法糖:
父传子:
父组件 :父组件内的写法与上面setup函数类似,在setup语法糖中,定义的变量不需要return,可直接使用。
子组件 :子组件需要引入一个新的API:‘defineProps’,用来接收父组件传来的数据。接收来的值不用return,可直接使用。
<!-- setup语法糖 父传子 -->
<!-- 父组件 -->
<template>
<div>
<hello-world :msg="val"></hello-world>
</div>
</template>
<script setup>
import { ref } from "vue";
import HelloWorld from "../components/HelloWorld.vue";
let val = ref("setup------语法糖");
</script>
<!-- 子组件 -->
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script setup>
import { defineProps } from "vue";
defineProps({
msg: String,
});
</script>
子传父:
父组件内的写法与上面setup函数类似。
子组件需要引入一个新的API:‘defineEmits’,用来向父组件传递数据。定义emit时把父组件绑定的事件名写在里面。点击传参时,第一个参数为事件名,第二个参数为传递的数据。
<!-- setup语法糖 子传父 -->
<!-- 父组件 -->
<template>
<div>
<h1>{{ val }}</h1>
<hello-world @son="chuan"></hello-world>
</div>
</template>
<script setup>
import { ref } from "vue";
import HelloWorld from "../components/HelloWorld.vue";
let val = ref("");
let chuan = (v) => {
val.value = v;
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="btn()">点击</button>
</div>
</template>
<script setup>
import { defineEmits } from "vue";
const emit = defineEmits(["son"]);
const btn = () => {
emit("son", "123");
};
</script>
遇见问题及解决:
setup函数在引入组件时,会标红,虽不影响代码运行,但是看着不舒服。
解决办法:找到"Vetur" 插件,禁用即可。