1

I have child component and want to pass some data to it's parent. My child component looks like:

// <button @click="sendClick($event)">Send</button>
// ...
data: function (){
    return {
            mycode: ""
        }
    },
    methods: {
        sendClick(e)
        {
            bus.$emit('change', this.mycode);
        }
}

My parent component looks:

var app = new Vue({
  el: '#app',
  data: {
    currentView: 'past-form',
    mycode: ''
  },
  methods:
  {
    changeView()
    {
        this.currentView = 'past-form'
        console.log(this.mycode);
    },

  }, 

  created()
  {
        bus.$on('change', function(mycode){
            this.mycode = mycode;

        });
  }

})
  1. I haven't found a better place for placing bus.$on (bus is declared globally) than in created(), but the docs state that created() is for stuff that should be initialized after the page is loaded. The created() block works; I checked it by placing in it console.log(this.mycode), but should I move emit handler somewhere else?

  2. It's look like my code does not execute mycode: '', because console.log(this.mycode); does not print anything.

Bert
  • 80,741
  • 17
  • 199
  • 164
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145

1 Answers1

1

As I mentioned in the comment, if your component is a direct child of your Vue, then there is no need for a bus.

That said, the created handler is fine for adding your bus event handler.

I expect the issue you have is a this issue. Try changing your handler to

bus.$on('change', mycode => this.mycode = mycode)

See How to access the correct this inside a callback?

Here is an example.

console.clear()

const bus = new Vue()

Vue.component("child", {
  template: `<button @click="sendClick($event)">Send</button>`,
  data: function() {
    return {
      mycode: "something"
    }
  },
  methods: {
    sendClick(e) {
      bus.$emit('change', this.mycode);
    }
  }
})

var app = new Vue({
  el: '#app',
  data: {
    currentView: 'past-form',
    mycode: ''
  },
  methods: {
    changeView() {
      this.currentView = 'past-form'
      console.log(this.mycode);
    },

  },

  created() {
    bus.$on('change', mycode => {
        this.mycode = mycode
        this.changeView()
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <child></child>
  Parent mycode: {{mycode}}
</div>
Bert
  • 80,741
  • 17
  • 199
  • 164