Loading... <h2>一、组件之间的关系</h2><p>在实际开发中,组件最常见的关系分为父子关系,兄弟关系</p><h2>二、组件之间的数据共享</h2><p><strong>2.1、父组件向子组件</strong><br> 父组件向子组件共享数据需要使用自定义属性。示例代码如下</p><pre><code> <!-- 父组件 --> <Left :msg="message" :user="userinfo"></Left> </code></pre><p><img src="https://www.xxhzm.cn/usr/uploads/2021/12/2429301948.png" alt="1.png" title="1.png"style=""></p><p>子组件使用props进行接受,示例代码:</p><pre><code> props: { msg: {}, user: {}, }, </code></pre><p><img src="https://www.xxhzm.cn/usr/uploads/2021/12/559374729.png" alt="2.png" title="2.png"style=""></p><p><strong>2.2、子组件向父组件共享数据</strong><br> 子组件向父组件共享数据需要使用自定义事件,示例代码如下</p><p>子组件:</p><pre><code> this.$emit("num", this.count); // num为自定义事件,实参为count</code></pre><p><img src="https://www.xxhzm.cn/usr/uploads/2021/12/3118572670.png" alt="3.png" title="3.png"style=""></p><p>父组件:</p><pre><code> <Right @num="newcount"></Right> // 定义num自定义事件,调用newCount函数 methods:{ newcount(val){ this.countSon = val // 将传来的实参复制给countSon } }, </code></pre><p><strong>2.3、兄弟组件之间数据共享</strong></p><p>在vue2.x中兄弟组件共享数据使用的是EventBus</p><p>EventBus的使用步骤</p><ol><li>创建 eventBus.js 模块,并向外共享一个 Vue 的实例对象</li><li>在数据发送方,调用 bus.$emit('事件名称', 要发送的数据) 方法触发自定义事件</li><li>在数据接收方,调用 bus.$on('事件名称', 事件处理函数) 方法注册一个自定义事件</li></ol><p>示例代码:</p><p>发送方:</p><pre><code>import bus from "@/components/enevtBus.js"; methods: { send() { // 通过eventbug发送数据 bus.$emit("share", this.str); }, }, </code></pre><p>接收方:</p><pre><code>import bus from "@/components/enevtBus.js"; created() { // 获取left组件传过来的str bus.$on("share", (val) => { this.strFromLeft = val; }); }, </code></pre><p>eventbus:</p><pre><code>import Vue from 'vue' export default new Vue() </code></pre> 猜你想看 PHP数组的定义与使用 jQuery图片移动 vue2使用ajax发送网络请求 Linux 系统安装部署 Redis 完全指南 Go编码规范 go语言数组 JS离开窗口改变title 每日一学:PHP 中的array_pop函数详解 axios封装token示例 总结一下nuxt3踩过的坑 最后修改:2022 年 06 月 05 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏
2 条评论
上面第一个例子props如果没有对参数进行限制的话其实可以写成 props: ['msg', 'userInfo'] 会更简单一点,当然如果需要定义初始值或者类型之类的就要传入Object了,例如https://v3.cn.vuejs.org/guide/component-props.html#props
当然这个类型好像会在编译的时候进行检测,实际运行起来如果传递的不对也可能可以正常运行,就像TypeScript
::BZ:re_miao:: 妙啊