Home > database >  What is the best way to add external JS components to Vue App?
What is the best way to add external JS components to Vue App?

Time:04-06

I wanted to add the TradingView widget to my Vue app. However I am wondering what is the best approach for embedding external JS component like TradingView widget to the Vue app?

For example this one:

<div >
  <div id="tradingview_6a746"></div>
  <div ><a href="https://www.tradingview.com/symbols/NASDAQ-AAPL/" rel="noopener" target="_blank"><span >AAPL Chart</span></a> by TradingView</div>
  <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
  <script type="text/javascript">
  new TradingView.widget(
  {
  "autosize": true,
  "symbol": "NASDAQ:AAPL",
  "interval": "D",
  "timezone": "Etc/UTC",
  "theme": "dark",
  "style": "1",
  "locale": "en",
  "toolbar_bg": "#f1f3f6",
  "enable_publishing": false,
  "allow_symbol_change": true,
  "container_id": "tradingview_6a746"
}
  );
  </script>
</div>

Taken from: https://www.tradingview.com/widget/advanced-chart/

Should I add the script tag in the index.html file? Or should I somehow add it to the script part in the Vue component? Not sure what is the most natural approach for this kind of external JS code?

CodePudding user response:

A simple and effective way to solve this is by using <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script> in your index.html . and put new TradingView.widget({... into the vue mounted() of your component.

CodePudding user response:

There are no drawbacks but adding you script in mounted() is more practical .Let's take fontAwesome as an example :

mounted() {
      let fontAwesome = document.createElement('script')
      fontAwesome.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js')
      document.head.appendChild(fontAwesome)
    },

In this way registering script will give you your functions access in global object window.

For example, now I can access some of the cool properties of FontAwesome like this:

window.FontAwesome.config
  • Related