happyDemon / vue-echo

Vue integration for the Laravel Echo library.
228 stars 24 forks source link

Using 'this' in channel:'user.' + this.user.id #13

Closed GordonChen13 closed 7 years ago

GordonChen13 commented 7 years ago

can I do something like this to apply current vue instance scope in channel: 'user.' + this.user.id

channel: function (vm) {
return 'user.' + vm.user.id;
}
happyDemon commented 7 years ago

If the user property has been defined before you return it here it should be fine.

GordonChen13 commented 7 years ago

But I got error like this:

[Vue warn]: Error in created hook: "TypeError: e.startsWith is not a function"

app.js:6812 TypeError: e.startsWith is not a function
    at app.js:99918
    at VueComponent.created (app.js:99918)
    at callHook (app.js:8911)
    at VueComponent.Vue._init (app.js:10472)
    at new VueComponent (app.js:10642)
    at createComponentInstanceForVnode (app.js:9924)
    at init (app.js:9741)
    at app.js:9941
    at createComponent (app.js:11393)
    at createElm (app.js:11336)

even console.log(vm) get the same error. I think channel: function (vm) { return 'user.' + vm.user.id; } wasn't support yet. I can use this.$echo.channel() function to get what I need , But if it can support channel:..... ,it is better. Thanks a lot!

happyDemon commented 7 years ago

oh, I'm sorry, I read through that too quickly while I was at work.

but you're right, only strings are currently supported. I'll see if I can whip something up this weekend.

My main worry is though, is that the channel gets initialised on the created hook. So the user info, or at least the id should be present before that happens. Accessing the VM does not seem like the most logical option, unless you're pulling in data and setting it to the VM in the beforeCreate hook.

tomlankhorst commented 6 years ago

You could join a channel in mounted and unsubscribe manually in beforeDestroy.

export default { 
  // data: ... 
  mounted: function(){
    this.$echo.channel('My.Channel.'+this.me); //... etc. 
  },
  beforeDestroy: function(){
    this.$echo.leave('My.Channel.'+this.me)
  }
}