search

Home  >  Q&A  >  body text

javascript - How to update data in $on in Vue2.0

Because the communication is not between father and son, I followed the online tutorial to create a bus.js file
import Vue from 'vue'
export default new Vue()

The first component login.vue is used for $emit
this.usermsg is an object

 bus.$emit('usermessage', this.usermsg)
 this.$router.push({name: 'mine'})
 

The first component mine.vue is used for $emit
data() {

  return {
    userData: {},
  }
},
created() {
  bus.$on('usermessage', (usermsg) => {
    console.log(this.msg)
    console.log(usermsg.name)
    this.userData= usermsg
    console.log('mine接收到的usermsg')
    console.log(this.userData)
  })
  
  mounted() {
  console.log(this.userData)
  }

The data of userData will not be changed, and the assignment will not take effect. Is this pointing to the wrong point, or should I not change the assignment like this? I have tried many methods, and I am confused

欧阳克欧阳克2755 days ago646

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-12 09:27:46

    First of all, your mine.vue must be initialized first. After $on('usermessage'), the relevant code triggers $emit('usermessage') before receiving this event. According to your current code, when you emit, mine.vue has not been initialized at all, so this event cannot be monitored.
    Then, your this pointing is correct because you used an arrow function. For details, please see the this pointing issue of arrow functions. (Although I don’t know what you want to do with this.msg, there is obviously no msg in the data)
    In addition, your idea is to log in to obtain the user information and display it on the mine.vue page. It is recommended that you use vuex to save the user information, so that you can Got it on another page

    reply
    0
  • 三叔

    三叔2017-06-12 09:27:46

    Correct answer upstairs;
    When jumping to login, the mine component will be destroyed. You can print something in the destroyed life cycle to see if it is correct. In this way, when you jump to mine again, the content inside will be re-initialized, so that what you print out will always be the content that has just been initialized and has not been operated on.

    reply
    0
  • Cancelreply