导航到另一个页面时如何删除外部JS VUEJS

How to remove external JS when navigate to another page VUEJS

我在带有外部 js 的主组件中有 java 脚本组件。当页面导航到另一个页面时,我需要删除外部 js。页面不刷新。

<script>
  function initFreshChat() {
    window.fcWidget.init({
      token: "***",
      host: "https://wchat.freshchat.com"
    });
  }
  function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);
</script>

这是外部js:https://wchat.freshchat.com/js/widget.js

我需要这个,因为我需要在一页中保留这个新鲜聊天 window。 这可以通过设置任何条件来完成。但如果我们刷新页面,它就会起作用。这里的页面根本不刷新。 因此,当导航到另一个页面时,我需要删除外部 js。当来到这个页面时返回。

您可以将脚本包装在 Vue 组件生命周期中,

  • 渲染
  • 移除
  • 刷新

随时需要。

我在 codepen 上找到了这段代码 https://codepen.io/akccakcctw/pen/LBKQZE

Vue.component("fc-button", {
template: "#fcButton",
props: {
 fc: {
   type: Object,
   default: {},
 }
 
},
methods: {
 openWidget: function() {
   document.getElementById("fc_frame").style.visibility = "visible";
   window.fcWidget.open();
 }
}
});

const vm = new Vue({
el: "#app",
data: function() {
 return {
   fc: {
     isInit: false,
   },
 };
},
mounted: function() {
 var self = this;
 window.fcSettings = {
   token: "8d3a4a04-5562-4f59-8f66-f84a269897a1",
   host: "https://wchat.freshchat.com",
   config: {
     cssNames: {
       widget: "custom_fc_frame",
       open: "custom_fc_open",
       expanded: "custom_fc_expanded"
     },
     headerProperty: {
       hideChatButton: true
     }
   },
   onInit: function() {
     
     window.fcWidget.on("widget:loaded", function() {
       self.fc.isInit = true;
       window.fcWidget.on("unreadCount:notify", function(resp) {
         console.log(resp);
         test = resp;
         if (resp.count > 0) {
           // document.getElementById('notify').classList.add('h-btn-notify');
           document.getElementById("notify").style.visibility = "visible";
         } else if (resp.count == 0) {
           // document.getElementById('notify').classList.remove('h-btn-notify');
           document.getElementById("notify").style.visibility = "hidden";
         }
       });
       window.fcWidget.on("widget:closed", function() {
         document.getElementById("fc_frame").style.visibility = "hidden";
         document.getElementById("open_fc_widget").style.visibility =
           "visible";
       });
       window.fcWidget.on("widget:opened", function(resp) {
         document.getElementById("open_fc_widget").style.visibility =
           "hidden";
       });
     });
   }
 };
}
});