search

Home  >  Q&A  >  body text

javascript - How to change data() under created hook in vue?

This is what I write in my component:

A navigation bar

<p class="navbar" v-show="showNavbar">


//js
import Bus from '../../common/js/bus'
export default {
data () {
  return {
    showNavbar: true
  }
},
created () {
  Bus.$on('hideNavbar', function (h) {
    if (h === 1) {
      this.showNavbar = true
    } else if (h === 2) {
      this.showNavbar = false
      console.log('false')
    }
  })

I hope to monitor the status of hideNavbar through Bus.$on, but the browser console reports that showNavbar is not defined
Is there something wrong?

高洛峰高洛峰2825 days ago629

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:36:46

    Try using the arrow function. It should be that the current this is not assigned to the current vue example

    reply
    0
  • Cancelreply