[Vuejs]-How to import a script into .vue file?

1๐Ÿ‘

You should use Mixins. Make your own mixin and then add the methods from imported script inside methods section of mixin.

  var mixin = {
  methods: {
    foo: function () {
      console.log('foo')
    },
    conflicting: function () {
      console.log('from mixin')
    }
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    bar: function () {
      console.log('bar')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})
๐Ÿ‘คzivce

1๐Ÿ‘

One possible solution is adding external script in created() hooks and use script onload method

    <template>
      .... your HTML
    </template>

    <script>
    export default {
        data: () => ({
            url: 'http://www.streambox.fr/playlists/x36xhzz/x36xhzz.m3u8',
            player: null
        }),
        created() {
            let clapprScript = document.createElement('script')
            clapprScript.setAttribute('src', 'https://cdn.jsdelivr.net/npm/clappr@latest/dist/clappr.min.js')
            clapprScript.onload = this.initPlayer;
            document.head.appendChild(clapprScript)
        },
        methods: {
            initPlayer() {
                this.player = new Clappr.Player({
                    source: this.url,
                    parentId: "#vplayer",
                    height: 240,
                    width: 320
                })
                console.log('Player is loaded')
            }
        }
    }
    </script>
๐Ÿ‘คittus

0๐Ÿ‘

You should be able to do this, after installing Clappr with npm:

<script>
  import Clappr from 'clappr';
  export default {
      created() {
          let player = Clappr.Player({...});
      }
  }
</script>

This way you can initialize your clappr instance in the Vue component just as you would in vanilla html, js scenario.

๐Ÿ‘คBorisu

Leave a comment