vue3父子传参 教学局(包含vite和cli)

编程入门 行业动态 更新时间:2024-10-26 20:26:28

vue3<a href=https://www.elefans.com/category/jswz/34/1769150.html style=父子传参 教学局(包含vite和cli)"/>

vue3父子传参 教学局(包含vite和cli)

注:使用之前先引用 

 1.简单介绍 ref 和reactive

一、父传子以及子传父(共两个方法)

父组件

子组件接受

(方法一)

 方法二

 

父组件代码:

<template><div><div>hello World</div><div>{{ name }}</div><div>{{ job.salary }}</div><div>{{ textName }}</div><button @click="getName">显示信息</button><input type="text" v-model="name" /><helloworld:job="job"v-model:name="name"@cancel="toastCancel"></helloworld></div>
</template><script>
import { ref, watch,reactive } from "vue";
import helloworld from "../components/HelloWorld.vue";
import { useRouter } from "vue-router";
export default {name: "HomeView",components: {helloworld,},setup() {const contantNumber=ref(0)  //contantText  给他赋值为0(ref一般定义基础类型,字符串,数字,true)const state=reactive({type: "前端工程师",salary: 0,})  //state 赋值对象(reactive一般定义对象或数字也可以定义基础类型)const router = useRouter();let name = ref("hello");let job = reactive({type: "前端工程师",salary: 0,});watch(job, (newValue) => {console.log("数据变化了", newValue);});let textName = reactive("world");const getName = async () => {try {let data = await axios.get("/apis/hmcsSecurity/v3/user/authInfo", {params: {appId: 1,areaLayer: "bbbbbbbb",userName: "yanghaodong1",},});return data;} catch (e) {console.log("[ e ] >", e);}job.salary = job.salary + 1;router.push({ path: "/textView" });};function toastCancel(val) {console.log("[val  ] >", val);}let fatherToSon = ref("给你");return {name,getName,job,textName,toastCancel,fatherToSon,};},
};
</script>

子组件代码:

<template><button @click="cancel">点击</button>
</template><script setup>
import { reactive, watchEffect, watch } from "vue";
const props = defineProps({//接受父组件传过来的属性fatherToSon: {type: Number, //类型default: 0, //默认值},job: {type: Object,},
});
let num = reactive(0);
const emit = defineEmits(["cancel",]); //接受父组件传过来的事件
// 默认immediate:true
watchEffect(() => {//用到谁,监视谁const x = fatherToSon;console.log("我被触发了", x);
});
watch(//比watchEffect 要快[() => job.salary, () => fatherToSon, "update:name"],(newValue) => {console.log("数据变化了s", newValue);},{ deep: true }
);
const cancel = () => {emit("update:name", "你好吗"); //更细父组件的name  注:父组件传参必须添加v-modelemit("cancel", num);
};
</script><style lang="scss" scoped></style>

更多推荐

vue3父子传参 教学局(包含vite和cli)

本文发布于:2024-03-06 17:22:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1715918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:父子   cli   vite

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!