vue3组合式api <script setup> props 父子组件的写法
父组件传入子组个的变量, 子组件是无法直接修改的, 只能通过 emit的方式, 让父组件修改, 之后子组件更新
<template>
<div class="parent">
我是父组件
<son :msg="msg" :obj="obj" @changemsgEmit="changemsgEmit" @changeobjnameEmit="changeobjnameEmit" @changeobjageEmit="changeobjageEmit"></son>
</div>
</template>
<script setup>
import {ref, reactive} from "vue";
import son from "./son.vue"
let msg = ref("this msg form parent.vue");
let obj = reactive({
name:"huang",
age:39
})
const changeobjageEmit = (params)=>{
obj.age = params;
}
const changeobjnameEmit = (params)=>{
obj.name = params.newname;
}
const changemsgEmit = (params)=>{
console.log(params);
msg.value = params.join("");
}
</script>
<style scoped>
</style>
父组件的写法没有变, 子组件的写法就有很大的变化了
<template>
<div class="son">son
{{msg}}
<hr/>
{{obj.name}}
{{obj.age}}
</div>
<button @click="changemsg">changemsg</button>
<button @click="changeobjname(3)" type="button">changeobjname</button>
<button @click="changeobjage(42)" type="button">changeobjage</button>
</template>
<script setup>
//这里定义了一个 props来接收传来的属性
//使用时可以是 {{msg}} 也可以使用 {{props.msg}}
let props = defineProps({
msg:{
type:String,
default:""
},
obj:{
type:Object,
default:{}
}
})
//这里定义了三个自定义事件
const emit = defineEmits(["changeobjnameEmit","changeobjageEmit","changemsgEmit"]);
//下面是通过事件调用了三个自定义的事件
const changeobjname = ()=>{
let objname = {newname:"hahaha"}
emit("changeobjnameEmit",objname)
}
const changeobjage = (age)=>{
emit("changeobjageEmit",age)
}
const changemsg = ()=>{
emit("changemsgEmit",["aa","bb","cc"]);
}
</script>