javascript - How to update data in $on in Vue2.0
欧阳克
欧阳克 2017-06-12 09:25:46
0
2
617

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

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(2)
过去多啦不再A梦

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

三叔

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template