父组件传入子组个的变量, 子组件是无法直接修改的, 只能通过 emit的方式, 让父组件修改, 之后子组件更新文章来源:https://www.toymoban.com/news/detail-691284.html
<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>
父组件的写法没有变, 子组件的写法就有很大的变化了文章来源地址https://www.toymoban.com/news/detail-691284.html
<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>
到了这里,关于vue3组合式api <script setup> props 父子组件的写法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!