Pass Data

01 Jan 2024 . vue .

Parent to child

Use component’s props property.

const cpn = {
  template: "#cpn",
  props: { 
          cmessage: {
          type: String,
          default: 'zzzzz',
          required: true
          }
  }
}
<div id="app">
    <cpn :cMessage="message"></cpn>
</div>
<script>    
const app = new Vue({
      el: "#app",
      data: {
        message: "你好",
      },
      components: {
        cpn
      }
    })
  </script>


Child to parent

In child component, use $emit, first parameter is event name and the second is passed value.

methods: {
        btnClick(item) {
          this.$emit('itemclick', item)
        }
      },

In child component, listen click event and call the method.

<div>
      <button v-for="(item, index) in categoties" :key="index" @click="btnClick(item)"></button>
</div>

In parent component, define a method.

methods: {
	cpnClcik(item) {
		console.log('cpnClick'+item.name);
	}
},

In parent component, listen the event passed by child component.

<cpn @itemclick="cpnClcik"></cpn>

Siblings

Use eventbus.

		<div id="app">
      <brother></brother>
      <sister></sister>
    </div>
    <script>
      var enveBus = new Vue()
      Vue.component('brother', {
        data() {
          return {
            kk: ''
          }
        },
        methods: {
          dd() {
            enveBus.$emit('bTs', 'brother->sister')
          }
        },
        template: `
          <div>
          <button @click='dd'>brother---</button>
          </div>
        `,
        mounted() {
          enveBus.$on('asd', (result) => {
            this.kk = result
          })
        }
      })
      Vue.component('sister', {
        data() {
          return {
            sis: ''
          }
        },
        template: `
          <div>
          <button @click="cc">sister---</button>
          </div>
        `,
        mounted() {
          enveBus.$on('bTs', (message) => {
            this.sis = message
          })
        },
        methods: {
          cc() {
            enveBus.$emit('asd', 'sister->brother')
          }
        }
      })
      var vm = new Vue({
        el: '#app',
        data: {},
        methods: {}
      })
    </script>