Vue父子组件

Dax

2021-08-13

2009 0 0

几种常见的通信方式:

1、prop 属性

父组件通过绑定属性的方式,给子组件传值,同时子组件通过设置 props 来接收

<div id="app"> <child :content="msg"></child> </div> <script> let Child = Vue.extend({ template: '<h1>{{content}}</h1>', props: { content: { type: String, default: () => { return 'from child' } } } }) new Vue({ el: '#app', data: { msg: 'hello' }, components: { Child } }) </script>

 2、$emit

子组件通过调用 this.$emit(‘事件’,‘参数’) 给父组件通信,父组件通过监听 子组件的事件,来获取

<div id="app"> <v-button @parent="handleParent"></v-button> </div> <script> let vButton = Vue.extend({ template: '<button @click="handleClick"></button>', data: { tragger: 'hello vue' }, methods: { handleClick() { this.$emit('parent', this.tragger) } } }) new Vue({ el: '#app', data: { content: '' }, methods: { handleParent(val) { this.content = val } }, components: { vButton } }) </script>

 3、属性attrs 和 $listeners

4、EventBus (bus 总线)

思路就是声明一个全局Vue实例变量 EventBus , 把所有的通信数据,事件监听都存储到这个变量上。这样就达到在组件间数据共享了,有点类似于 Vuex,但复杂的项目还是用 Vuex

子组件通过 EventBus.$emit() 向外触发事件,父组件通过EventBus.$on() 来监听该事件,变量保存在EventBus

5、Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 6、通过ref 属性

//父组件

<template> <div> <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child"/> </div> </template> <script> import Child from './child'; export default { methods: { handleClick() { this.$refs.child.navigate(); }, }, } </script>

//子组件

<template> <div>我是子组件</div> </template> <script> export default { methods: { navigate() { console.log('我是子组件的方法'); }, }, }; </script>   
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

vue最新面试题

最近在面试,总结几个重点的面试题:一、vue父子组件之间的传值:简单来说,子组件通过props方法接受父组件传来的值,子组件通过$emit方法来向父组件发送数据。(具体案例可以看我之前写的博客)。二、vue生命周期函数:beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestr

vue的8种通信方式

1.props/emit1.父组件向子组件传值下面通过一个例子说明父组件如何向子组件传递数据:在子组件article.vue中如何获取父组件section.vue中的数据articles:\'红楼梦','西游记','三国演义'\//section父组件<template<divclass"section"

React 组件间通信的10种方法

组件间通信方式总结父组件子组件:1.Props2.InstanceMethods子组件父组件:1.CallbackFunctions2.EventBubbling兄弟组件之间:1.ParentComponent不太相关的组件之间:1.Context2.Portals3.Global