A variety of ways (props, $ ref, $ emit, $ attr, $ listeners) Vue component in communication

The difference between the prop and $ ref:

prop focuses on data transfer, it does not call the subassembly in the properties and methods. When you create articles like components, custom title and content of such usage scenarios, most suitable prop.

$ Ref focused on the index, used to call the main sub-components in the properties and methods, it is not good at data transfer. And when used in ref dom element, to make the role of the selector, this function is used more often than as an index.

props pass parent component value subassembly

Parent component by value

// The props example (VUE) 
<Template> 
    <div ID = "App"> <Child: Message = "Message"> </ Child> dynamic transmission
      
    <Child message = "content delivery"> </ child> static transfer
    </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:'I from parent element' , 
            MSG: 'default' 
          } 
      }, 
      Created () {}, 
      Mounted () { }, 
      Methods: {} 
    }

 </ Script> 

<style lang = "SCSS" scoped> 

</ style>

Subassembly receiving parent component values ​​pass

<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>

Parent component subassembly reference code, can be achieved by traditional values ​​props. It can be passed string, number, object, expression. For receiving subassembly parent component The props, can be used directly props: [ 'xxxx'] format, in order to more rigorous, may be used in the following manner:

<script>
    export default {
      name: "child",
     // props:['message'],
      props:{
        message:{
          type:Object,
          default:function () {
            return {}
          }
        }
      },
      data() {
         return {
            title:''
         }
      },
      mounted() {
         // this.$emit('showMessage','我是来自子组件')
      },
      methods:{
      }
    }
</script>

 

 


 

 

$ Emit sub-assemblies pass values ​​to the parent component

props, ref = parent components are implemented> communication between the subassembly, and the subassembly can be achieved $ EMIT more widely to the communication, the application range of $ EMIT parent element.

Subassembly to the traditional values ​​parent component

Template> 
    <div> 
     <INPUT REF = "myBtn"> </ INPUT> 
    </ div> 
</ Template> 
<Script> 
  Export default { 
      name: "index" , 
      Data () { 
         return { 
            info: 'REF can be obtained element oh ~ ' 
         } 
      }, 
      Mounted () { 
          the this $ EMIT. (' showMessage ',' from the sub-assembly I ' ) 
      }, 
      Methods: { 
      } 
    }
 </ Script>

 

Receiving subassembly pass parent component values

<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:'Default ' 
      },
          }
      created() {

      },
      mounted(){
      },
      methods: {
        showMessage (data) {
          this.fromchildinfo = data
        },
      }
    }
</script>

 


 

 

Use the $ ref

Description:. Vm $ refs an object has been registered holders of all subcomponents ref's (or HTML elements)
use: in the HTML element, add a ref attribute, and then in JS by vm $ refs property to get.
Note: If the acquisition is a sub-assembly, the subassembly can be acquired in the data and methods ref by
adding attribute ref

<div id="app">
  <h1 ref="h1Ele">这是H1</h1>
  <hello ref="ho"></hello>
  <button @click="getref">获取H1元素</button>
</div>

Get registered ref all the components or elements 
Methods: { 
  getRef () { 
    // represents from $ refs object, attribute value acquired ref: h1ele DOM element assembly or 
    the console.log ( the this ; $ refs.h1Ele.innerText.)
    the this . refs.h1ele.style.color $ = 'Red'; // modified html form 

    the console.log ( the this $ refs.ho.msg.); // Get data component 
    the console.log ( the this $ refs.ho.. Test); // get the component approach 
  } 
}
<input ref="count" type="text" v-model="active.name" required name="name" value=""> 

  In this way, we can use vue $ ref to get the dom node, some operations dom

  The number of input box character control input: The following example

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
    }
  },
})

Used in the subassembly may be used to obtain the property value subassembly, which subassembly has assumed a property 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
scene proposed: A, B, C are three components required to achieve A => B => C, passed (simple structure, without using vuex). Of course, implementation can be $ emit, layer by layer, to pass along, but it seems the code redundancy. After vue2.4, raised $ attr, $ listeners, can achieve rapid delivery.
Component 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(),
          }
            MSG: 'default'
            title: '',
            info: 'I'm from the parent component'
      },
      created() {

      },
      mounted(){
      },
      methods: {
         getData (val) {
           this.msg = val
        },
      }

    }

</script>

<style lang="scss" scoped>
 #app {
   width: 375px;
   height: 100%;
 }
</style>

b Components

<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 Components

<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 wording of TypeScript

A component




         val;
    };
}
</script>

b Components

<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 Components

<Template> 
    <div> 
        <P> Sun assembly </ P> 
        <P> from grandparents: {{}} $ attrs.info </ P> 
        <Button @click = "$ EMIT ( 'sunchangedata', 'said grandchildren grandfather good ') "> click change grandparents information </ Button> 
    </ div> 
</ Template> 

<Script lang =" TS "> 
Import {the Component, Prop, Vue} from " VUE-Property-Decorator " ; 

Export default class the extends the Sun Vue { 
  
}
 </ Script> 

<style> 
</ style>

 

  

 

Guess you like

Origin www.cnblogs.com/mary-123/p/11691599.html