vue.js3:父组件子组件互相访问数据方法(vue@3.2.37)
一,js代码
1,Child.vue
<template>
<div style="background: #ffff00;">
<div>这是子组件</div>
<div>参数default:{{defaultStr}},参数top:{{topStr}}</div>
<div>变量:{{childName}}</div>
<button @click="childAlert">子组件alert</button><br/>
<button @click="sendFatherData">子组件向父组件发送数据</button><br/><br/>
</div>
</template>
<script>
import {ref} from 'vue';
export default {
name: "ChildComp",
props:['default','top'], //属性,用来接收参数
setup(props,{emit}) {
//本身的一个方法,响应点击
const childAlert = () => {
alert('这是子组件中的alert');
}
//接收到父组件调用时的参数
const defaultStr = ref(props.default);
const topStr = ref(props.top);
//定义变量
const childName = ref('红孩儿');
//向父组件发送数据
const sendFatherData = () => {
emit('eventMsg','寻找牛魔王');
}
return {
childAlert,
defaultStr,
topStr,
childName,
sendFatherData,
}
}
}
</script>
<style scoped>
</style>
2,Father.vue
<template> <div> <div>这是父组件</div> <child ref="child" default="cn" top="jp,us,uk" @eventMsg="childCall"></child> <button @click="callChildMethod">父组件调用子组件的方法</button><br/> <button @click="callChildData">父组件访问子组件的数据</button> </div> </template> <script> import {ref} from 'vue' import Child from './Child.vue' export default { name: "FatherComp", components:{ Child, }, setup() { // 获取子组件 const child = ref(null) //调用子组件中的方法 const callChildMethod = () => { child.value.childAlert(); } //访问子组件中的数据 const callChildData = () => { alert("子组件中的变量:childName:"+child.value.childName); } //接收子组件发送的数据 const childCall = (childData) => { alert("子组件传过来的参数:"+childData); } return { callChildMethod, callChildData, child, childCall, } } } </script> <style scoped> </style>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/06/02/vue-js3-fu-zu-jian-zi-zu-jian-hu-xiang-fang-wen-shu-ju-fang/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果

三,查看vue框架的版本:
liuhongdi@lhdpc:/data/vue/child$ npm list vue child@0.1.0 /data/vue/child ├─┬ @vue/cli-plugin-babel@5.0.6 │ └─┬ @vue/babel-preset-app@5.0.6 │ └── vue@3.2.37 deduped └─┬ vue@3.2.37 └─┬ @vue/server-renderer@3.2.37 └── vue@3.2.37 deduped
浙公网安备 33010602011771号