Vue组件内监听Intercom外部事件:onHide触发时修改组件状态
this Context Issue in Intercom Callbacks for Your Vue Component Hey there! The problem you're facing boils down to this context binding inside the Intercom event callbacks. When you pass a standard function to Intercom('onHide', ...), this inside that function doesn't point to your Vue component instance—it refers to a different context (usually the global window or the Intercom object itself). That's why trying to update this.open doesn't work as expected.
Here are three straightforward ways to fix this:
1. Use Arrow Functions (Most Concise Solution)
Arrow functions automatically inherit the this context from their surrounding scope, which in this case is your component's mounted hook. This ensures this correctly references your Vue component:
mounted: function() { if (typeof Intercom !== 'undefined') { Intercom('onUnreadCountChange', (count) => { if (count) this.notif_count = count; }); Intercom('onHide', () => { this.open = false; }); } }
2. Explicitly Bind this to the Callback
If you prefer using regular functions, you can use bind(this) to force the callback to use your component's context:
mounted: function() { if (typeof Intercom !== 'undefined') { Intercom('onUnreadCountChange', function(count) { if (count) this.notif_count = count; }.bind(this)); Intercom('onHide', function() { this.open = false; }.bind(this)); } }
3. Store the Component Context in a Variable
You can save a reference to your component's this in a variable (like vm or self) inside the mounted hook, then use that variable in the callbacks:
mounted: function() { const vm = this; // Capture the component context if (typeof Intercom !== 'undefined') { Intercom('onUnreadCountChange', function(count) { if (count) vm.notif_count = count; }); Intercom('onHide', function() { vm.open = false; }); } }
All three approaches will resolve the issue—arrow functions are typically the most modern and clean choice, but feel free to go with whichever fits your coding style best!
内容的提问来源于stack exchange,提问作者Wizzardzz

