Sunday, July 29, 2018

Passing data through arguments parameters in Vue

Passing data through arguments parameters in Vue

HTML:

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <p>Expected output: <code>{{ JSON.stringify(expected) }}</code></p>
  <component @emission="hearEmission">complete data, without extras</component>
  <component @emission="hearEmission('extra', ...arguments)">with extras, incomplete data</component>
  <component @emission="function (a, b, c) { hearEmission('extra', a, b, c) }">expected, overly explicit</component>
  
  <ol class="log">
    <li v-for="line in logs"><code>{{ JSON.stringify(line) }}</code></li>
  </ol>
</div>

Script:

Vue.component('component', {
 template: '<button @click="emitEvent"><slot></slot></button>',
  methods: {
   emitEvent: function() {
     this.$emit('emission', 1, 2, 3);
    }
  }
});

new Vue({
  el: '#app',
  data: {
   logs: [],
    expected: ['extra', 1, 2, 3]
  },
  methods: {
   hearEmission: function(extra, a, b, c) {
     this.logs.push([extra, a, b, c]);
      if (this.logs.length === 11) {
       this.logs.splice(0, 1);
      }
    }
  }
})

Reference:

https://jsfiddle.net/50wL7mdz/30115

No comments: