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)的更多相关文章

  1. vue组件通信的几种方式

    最近用vue开发项目,记录一下vue组件间通信几种方式 第一种,父子组件通信 一.父组件向子组件传值 1.创建子组件,在src/components/文件夹下新建一个Child.vue 2.Child ...

  2. vue—组件通信,ref

    组件通信: 父组件传递子组件: 把需要的数据 传递给 子组件的数据,以数据绑定(v-bind)的形式,传递到子组件内部,供子组件使用,缩写(:) 动态传递: 第一步:在父组件中的子组件标签中进行动态的 ...

  3. vue 组件通信

    组件 组件之间的数据是单向绑定的. 父组件向子组件通信 是通过子组件定义的props属性来实现.通过props定义变量与变量类型和验证方式. props简化定义 在简化定义中,变量是以数组的方式定义. ...

  4. vue组件通信那些事儿

    一.说说通信 通信,简言之,交流信息.交流结束后,把信息放在哪里,这是一个值得思考的问题.vue中保存状态有2种方式,组件内的data属性和组件外的vuex的state属性. 1.用state的场景 ...

  5. Vue组件通信之Bus

    关于组件通信我相信小伙伴们肯定也都很熟悉,就不多说了,对组件通信还不熟悉的小伙伴移步这里. 在vue2.0中 $dispatch 和 $broadcast 已经被弃用.官方文档中给出的解释是: 因为基 ...

  6. Vue - 组件通信之$attrs、$listeners

    前言 vue通信手段有很多种,props/emit.vuex.event bus.provide/inject 等.还有一种通信方式,那就是 $attrs 和 $listeners,之前早就听说这两个 ...

  7. vue组件通信全面总结

    写在前面 组件间的通信是是实际开发中非常常用的一环,如何使用对项目整体设计.开发.规范都有很实际的的作用,我在项目开发中对此深有体会,总结下vue组件间通信的几种方式,讨论下各自的使用场景 文章对相关 ...

  8. VUE 组件通信总结

    1.prop 父组件传递给子组件,即通过VUE本身具有的Props属性来传递值 Child组件 <template> <span>{{message}}</span> ...

  9. vue组件通信&&v兄弟组件通信eventbus遇到的问题(多次触发、第一次不触发)

    组件通讯包括:父子组件间的通信和兄弟组件间的通信.在组件化系统构建中,组件间通信必不可少的 (vuex以后再说). 父组件--> 子组件 1. 属性设置 父组件关键代码如下: <templ ...

随机推荐

  1. 分布式CAP与BASE理论

    参考: CAP和BASE理论 https://juejin.im/post/5d720e86f265da03cc08de74 https://github.com/changmingxie/tcc-t ...

  2. maven搭建webservice apache cxf实现

    用 web方式发布 webService 服务端.客户端 一.服务器端搭建 1.首先创建 一个web工程(增加Maven依赖) 2.增加Maven依赖包,如下: <project xmlns=& ...

  3. Prism_ViewModelLocator(5)

    ViewModelLocator ViewModelLocator用于绑定视图的DataContext,以使用标准命名约定的一个ViewModel的实例. Prism ViewModelLocator ...

  4. Angular(04)-知识点脑图

    点击左键 => 拖拽图片 => 新标签页查看图片 => 放大拖拽查阅

  5. 【iOS】Swipe与Pan区别分析

    By definition, a swipe gesture is necessarily also a pan gesture -- both involve translational movem ...

  6. 2、nio的例子实践

    下面的例子,说明了,nio中的三大核心类的基本使用.buffer,channel,selector package com.shengsiyuan.nio; import org.junit.Test ...

  7. http服务需要pycurl模块这样去监控服务

    最近运维还是比较空闲,写篇自己的心得体会.做过运维的应该都做过http服务了.像一些电子商城,或者是一些互联网公司,web的服务之类是至关重要的,近期看了刘天斯大哥的书觉得自己运维平台应该也可以这样去 ...

  8. leetcode题解:整数反转

    给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转. 示例 1: 输入: 123 输出: 321  示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出 ...

  9. August 18th, 2019. Week 34th, Sunday

    Fear doesn't shut you down, it wakes you up. 恐惧不会消磨你的意志,它能激发你的潜能. We all know that fear is powerful, ...

  10. 通过pywin32库来上传文件

    先来安装:pip install pywin32 辅助定位工具winspy下载地址:https://sourceforge.net/projects/winspyex/ 打开后是这玩意: 按住靶心拖拽 ...