vue.js3:父组件子组件互相访问数据方法(vue@3.2.37)
2023-09-14 09:01:18 时间
一,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://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: 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
相关文章
- Vue专题 02_计算属性(computed) VS 方法(methods)
- vue报错: ERROR TypeError: Cannot read property 'version' of undefined
- form layui vue 和_layui和vue的区别是什么?[通俗易懂]
- html使用vue axios,使用 Vue和axios
- 字符串有哪些_vue子组件emit方法失效
- Vue 组件通信六种方法
- Vue系列- - -Webpack深度讲解
- vue cli 3 升级到 vue cli 4 方法步骤及升级点总结「建议收藏」
- vue前端怎么解决跨域问题_前端跨域调用js方法解决方案
- vue改写数组方法_vue数组添加和删除
- vue 父组件调用子组件的函数_vue子组件触发父组件方法
- Vue子组件调用父组件的方法及传值「建议收藏」
- Vue子组件向父组件传值(this.$emit()方法)「建议收藏」
- vue父子组件传值props_vue子组件调用父组件的方法并传参
- vue父组件向子组件传值_vue什么是父子组件
- Vue(renren-fast_vue_master)项目目录结构[通俗易懂]
- 今天讲vue讲解专栏里的VUE组件
- springboot和vue交互产生跨域问题的解决办法(后端解决方法)
- Vue-slot插槽的所有使用方法
- vue如何二次封装一个高频可复用的组件
- Vue实现图片大图预览,v-viewer组件的使用方法演示
- vue.js入门篇之Vue.js 样式绑定
- 安装Vue on Linux:轻松搭建开发环境(linux安装vue)
- 使用Vue框架使用MSSQL数据库实现快速开发(vue mssql)
- Vue实时监测Redis变化(vue监控redis变化)
- 用Vue从Redis中获取强有力的数据(vue用redis中数据)