天天看點

vue中引用cdn中的js檔案或者json的用法

1、現在有一個js檔案要放在cdn上。 這個js檔案的内容如下   :var testArr = [{"a":1}]

2、我要在vue項目中使用這個變量(因為這個變量可能是經常變化的,但是不能變化一次就打包一次,是以将他放在cdn上,有使用的話直接改變cdn上的js檔案,就不用上線項目了),

3.在vue中  聲明引用這個變量的方法

export function importScript (path, success, error) {   

  var oS = document.createElement('script')

  oS.src = path

  document.getElementsByTagName('head')[0].appendChild(oS)

  oS.onload = function () {

    success && success()

  }

  oS.onerror = function () {

    error && error()

  }

}

4.在元件中使用

      import {importScript} from 'api/sortAdver'

      importScript("http://www.baidu.com/backstage/temp.js",data=>{console.log(testArr)})

5.說明  path是你要放的cdn位址,console.log(testArr)中的testArr就是你js檔案中的變量,這樣就可以使用了

繼續閱讀