Vue 组件通信的多种方式(props、$ref、$emit、$attr、 $listeners)
prop和$ref之间的区别:
prop 着重于数据的传递,它并不能调用子组件里的属性和方法。像创建文章组件时,自定义标题和内容这样的使用场景,最适合使用prop。
$ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。
props 父组件传值子组件
父组件传值
//props示例(vue)
<template>
<div id="app">
<child :message="message"></child> 动态传递
<child message="传递的内容"></child> 静态传递
</div>
</template> <script>
import Child from "./Child";
export default {
components: {Child},
name: "main-page",
data() {
return {
message:{
type:1,
name:'Admin',
},
a:2,
b:4,
c:'lalal'+Math.random(),
title:'',
info:'我是来自父组件',
msg:'默认'
}
},
created() {},
mounted(){},
methods: {}
} </script> <style lang="scss" scoped> </style>
子组件接收父组件传值
<template>
<div>
{{message}}
<!--<slot></slot>-->
</div>
</template> <script>
export default {
name: "child",
props:['message'],
data() {
return {
title:''
}
},
mounted() {},
methods:{}
}
</script> <style lang="scss" scoped>
</style>
父组件code引用子组件,通过props可以实现传值。可以传递string , number , object,表达式。对于子组件接受父组件props,可以直接使用props:[‘xxxx’]格式,为了更严谨,可以使用如下方式:
<script>
export default {
name: "child",
// props:['message'],
props:{
message:{
type:Object,
default:function () {
return {}
}
}
},
data() {
return {
title:''
}
},
mounted() {
// this.$emit('showMessage','我是来自子组件')
},
methods:{
}
}
</script>
$emit 子组件向父组件传值
props、ref 实现的都是父组件=>子组件之间的通信,而$emit则可实现子组件向父组件的通信, $emit应用的范围较为广泛。
子组件传值给父组件
template>
<div>
<input ref="myBtn"></input>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
info:'ref可以获取到元素哦~'
}
},
mounted() {
this.$emit('showMessage','我是来自子组件')
},
methods:{
}
}
</script>
父组件接收子组件传值
<template>
<div id="app">
<child @showMessage="showMessage"></child>
</div>
</template> <script>
import Child from "./Child";
export default {
components: { Child},
name: "main-page",
data() {
return {
message:{
type:1,
name:'Admin',
},
fromchildinfo :'我是来自父组件',
msg:'默认'
}
},
created() { },
mounted(){
},
methods: {
showMessage (data) {
this.fromchildinfo = data
},
}
}
</script>
$ref 的使用
说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素)
使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取
注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods
添加ref属性
<div id="app">
<h1 ref="h1Ele">这是H1</h1>
<hello ref="ho"></hello>
<button @click="getref">获取H1元素</button>
</div>
获取注册过 ref 的所有组件或元素
methods: {
getref() {
// 表示从 $refs对象 中, 获取 ref 属性值为: h1ele DOM元素或组件
console.log(this.$refs.h1Ele.innerText);
this.$refs.h1ele.style.color = 'red';// 修改html样式 console.log(this.$refs.ho.msg);// 获取组件数据
console.log(this.$refs.ho.test);// 获取组件的方法
}
}
<input ref="count" type="text" v-model="active.name" required name="name" value="">
这样在vue中我们可以使用$ref来获取dom节点,进行一些dom的操作
下面示例:控制input输入框的文字个数
new Vue({
el:'#app',
data:{
active:{'name':''}
},
watch:{
active:{
handler:function(){
var _this = this;
var _sum = 4; //字数限制为4个
_this.$refs.count.setAttribute("maxlength",_sum);
},
deep:true
}
},
})
使用在子组件上,可以用来获取子组件的属性值,假设子组件里面都有一个属性news
<!-- 父组件 -->
<div id="app">
<hdnews ref="hdnews"></hdnews>
<hdinfo ref="hdinfo"></hdinfo>
</div>
new Vue({
el:'#app',
mounted () {
console.log(this.$refs.hdnews.news); //获取子组件的值
console.log(this.$refs.hdinfo.news);
this.$refs.msg.getMessage('我是子组件一!') //调用子组件的方法
}
})
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
data(){
return{
news:'我是子组件的数据'
}
},
methods:{
getMessage(m){
this.message=m;
}
}
}
</script>
$attr、 $listeners
场景提出:A、B、C三个组件,需要实现A=>B=>C,进行传递(结构较为简单,无需使用vuex)。当然实现方式也可以$emit,一层一层传递下去,但这样代码显得冗余。在vue2.4之后,提出 $attr、 $listeners ,可以实现快速传递。
组件A code:
<template>
<div id="app">
<son :info="info" @getData="getData"></son>
<div>{{msg}}</div>
</div>
</template> <script>
import Son from "./son"; export default {
components: {
Son,
Test,
Child},
name: "main-page",
data() {
return {
message:{
type:1,
name:'Admin',
},
a:2,
b:4,
c:'lalal'+Math.random(),
title:'',
info:'我是来自父组件',
msg:'默认'
}
},
created() { },
mounted(){
},
methods: {
getData (val) {
this.msg = val
},
} } </script> <style lang="scss" scoped>
#app {
width: 375px;
height: 100%;
}
</style>
b组件
<template>
<temp-son v-bind="$attrs" v-on="$listeners"></temp-son>
</template> <script>
import TempSon from "./tempSon"; export default {
components: {TempSon},
name: "son",
props:[]
}
</script> <style scoped> </style>
c组件
<template>
<div>
<h1 class="btn">{{this.$attrs.info}}</h1>
</div>
</template> <script>
export default {
name: "temp-son",
mounted() {
this.$emit('getData','我来自孙子组件')
}
}
</script> <style scoped> </style>
$attr、 $listeners 的TypeScript写法
A组件
<template>
<div class="home">
<img alt="Vue logo" src="@/assets/images/logo.png" />
<HelloWorld :info="info" @sunchangedata="getData" :msg="info" />
</div>
</template> <script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src @Component({
components: {
HelloWorld
}
})
export default class Home extends Vue {
info = "你不是好人?";
getData(val:any){
this.info = val;
};
}
</script>
b组件
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>hello hello 我是来自子组件</p>
<Sun v-bind="$attrs" v-on="$listeners"></Sun>
</div>
</template> <script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import Sun from "./sun.vue"; // @ is an alias to /src @Component({
components:{
Sun
}
})
export default class HelloWorld extends Vue {
inheritAttrs = false;
@Prop() private msg!: string;
}
</script> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less"> </style>
c组件
<template>
<div>
<p>sun组件</p>
<p>来自爷爷辈:{{ $attrs.info }}</p>
<button @click="$emit('sunchangedata','孙子说爷爷是好人')">点击更改爷爷辈信息</button>
</div>
</template> <script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator"; export default class Sun extends Vue { }
</script> <style>
</style>
Vue 组件通信的多种方式(props、$ref、$emit、$attr、 $listeners)的更多相关文章
- vue组件通信的几种方式
最近用vue开发项目,记录一下vue组件间通信几种方式 第一种,父子组件通信 一.父组件向子组件传值 1.创建子组件,在src/components/文件夹下新建一个Child.vue 2.Child ...
- vue—组件通信,ref
组件通信: 父组件传递子组件: 把需要的数据 传递给 子组件的数据,以数据绑定(v-bind)的形式,传递到子组件内部,供子组件使用,缩写(:) 动态传递: 第一步:在父组件中的子组件标签中进行动态的 ...
- vue 组件通信
组件 组件之间的数据是单向绑定的. 父组件向子组件通信 是通过子组件定义的props属性来实现.通过props定义变量与变量类型和验证方式. props简化定义 在简化定义中,变量是以数组的方式定义. ...
- vue组件通信那些事儿
一.说说通信 通信,简言之,交流信息.交流结束后,把信息放在哪里,这是一个值得思考的问题.vue中保存状态有2种方式,组件内的data属性和组件外的vuex的state属性. 1.用state的场景 ...
- Vue组件通信之Bus
关于组件通信我相信小伙伴们肯定也都很熟悉,就不多说了,对组件通信还不熟悉的小伙伴移步这里. 在vue2.0中 $dispatch 和 $broadcast 已经被弃用.官方文档中给出的解释是: 因为基 ...
- Vue - 组件通信之$attrs、$listeners
前言 vue通信手段有很多种,props/emit.vuex.event bus.provide/inject 等.还有一种通信方式,那就是 $attrs 和 $listeners,之前早就听说这两个 ...
- vue组件通信全面总结
写在前面 组件间的通信是是实际开发中非常常用的一环,如何使用对项目整体设计.开发.规范都有很实际的的作用,我在项目开发中对此深有体会,总结下vue组件间通信的几种方式,讨论下各自的使用场景 文章对相关 ...
- VUE 组件通信总结
1.prop 父组件传递给子组件,即通过VUE本身具有的Props属性来传递值 Child组件 <template> <span>{{message}}</span> ...
- vue组件通信&&v兄弟组件通信eventbus遇到的问题(多次触发、第一次不触发)
组件通讯包括:父子组件间的通信和兄弟组件间的通信.在组件化系统构建中,组件间通信必不可少的 (vuex以后再说). 父组件--> 子组件 1. 属性设置 父组件关键代码如下: <templ ...
随机推荐
- Effect:Mobile ocd
Satisfy the following two Keep your phone at all times Check your phone even if there's no news Alwa ...
- Bug 28450914 : ORA-600: [KDLRCI_GET_INLINE_DATA] SELECTING FROM CDB_FEATURE_USAGE_STATISTICS
alert日志报错: 2019-11-18T07:15:12.704938+08:00Errors in file /u01/app/oracle/diag/rdbms/sibcyb1/SIBCYB1 ...
- 小程序之--动态设置页面标题 wx.setNavigationBarTitle
参考地址 http://www.yilingsj.com/xwzj/2018-11-26/weixin-navigationbartitletext.html 页面最初是[在线教研] 可以在这个页面的 ...
- 五、如何通过CT三维图像得到DRR图像
一.介绍 获取DRR图像是医疗图像配准里面的一个重要的前置步骤:它的主要目的是,通过CT三维图像,获取模拟X射线影像,这个过程也被称为数字影响重建. 在2D/3D的配准流程里面,需要首先通过CT三维图 ...
- 搭建Harbor
搭建Harbor 一.安装准备 二.安装docker-ce 三.安装docker-compose 四.安装harbor 5.1下载安装程序 5.2配置harbor.yml 5.3运行install.s ...
- Linux下动态切换EHCI控制器下端口的速率(即切换为12M)
在sys目录下找到对应的控制器 例如:/sys/devices/platform/soc/ehci,直接操作该目录下的companion echo 1 > companion 将port1设 ...
- IT兄弟连 HTML5教程 CSS3揭秘 CSS3属性5
9 透明属性 元素透明也是我们常用的样式,在CSS2中使用滤镜属性opacity实现透明效果.现在有了CSS3的rgba属性,就不用这么麻烦了,当然这也得要浏览器支持才行.通常我们定义颜色都是用十六 ...
- C# 使用NAudio合并mp3、wav音频文件
1.什么是wav格式 WAV为微软公司(Microsoft)开发的一种声音文件格式,它符合RIFF(Resource Interchange File Format)文件规范,用于保存Windo ...
- window.innerHeight和document.documentElement.clientHeight区别
今天有人问我这个问题,做了个小例子来记录一下子. 首先这两个都是获取可视区域的高度,那他们有什么区别呢 1.window.innerHeight属于BOM(浏览器对象模型),而document.doc ...
- 一年半前端工作经验试水杭州:我是如何拿下网易、阿里和滴滴 offer 的
前言 笔者毕业于东北大学,大学毕业社招进入环球网,前端开发工程师一职.技术栈:React+node,Github 地址 成果 来到杭州的目标非常的明确,大厂.其实就是网易.阿里和滴滴.好在基本三家都拿 ...