Communication between parent and child groups in Vue

 

parent component code

<template>
  <div>
    <child @child-say="listenToBoy" :mes=count></child>
    <p>Do you like me?{{this.word}}</p>
  </div>
</template>
<script>
  import child from '@/components/child.vue'
  export default {
    name: "parent",
    data() {
      return {
        count: 0,
        word: ''
      };
    },
    components: {
      child
    },
    methods:{
        listenToBoy(text){
            if (!this.word){
                this.word = text
                console.log('111')
            }else{
                this.word = ''
                console.log('else')
            }
        }
    }
  }

</script>
<style lang="css" scoped>
</style>

  
subcomponent code

<template>
    <div>
        <p>{{message}}</p>
        <button @click="add">add</button>
        <button @click="onClickMe">Click</button>
    </div>
</template>
<script>
export default {
    name: "child",
    data () {
        return {
            message: this.mes,
            text: 'I love you'
        };
    },
    props: ['month'],
    methods: {
        add (){
            this.message ++
        },
        onClickMe(){
            this.$emit('child-say', this.text)
        }
    }
    }
</script>
<style lang="css" scoped>
</style>

  

1. Implemented the value of count to pass the value of the parent component to the child component through props, usage: The child component tag in the parent component is bound to a property and the value to be passed is followed by it (for example: mes=count, give Subcomponent identification) is passed, subcomponents are received with props:['mes'], and subcomponents are called with this.mes

2. The child component passes the value this.$emit() to the parent component, usage: the parent component listens to a property (such as @child-say='listenToBoy()'), and the formal parameter in the parent component method receives the child The value passed by the component (such as listenToBoy(text)),

The child component fires this.$emit('child-say', this.text) somewhere

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325123509&siteId=291194637