Search code examples
vue.jspackagecomponentscdn

Import and use Vue.js package from CDN


I am importing Vue.js & Vue-Toastify from a CDN to use on a SPA. I only need a couple of reactive components therefore am importing from CDN.

Vue Toastify

I am fairly new to Vue and am trying to use Vue-Toastify using the CDN // rather than installing and importing from npm. I have the correct CDN link but how do I import it to use in the .vue file. As I have not created a Vue.js project I do not have a main.js file nor can I use the import method.

Is this at all possible? If I console.log(window) I can see VueToastify in the list of modules but I am unable to use or access it from my .vue file.

Code samples currently installed via cdn:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-toastify@latest"></script>

but then the issue I have is then adding it into my .vue file. Currently I have:

let contactForm = new Vue({
    delimiters: ['[[', ']]'],
    el: '#contact-form',
    data: {
        form: new Form({
            name: '',
            email_address: '',
            message:''
        })
    },
    methods: {
        submit(){
            let formdata = new FormData()
            formdata.append('name', this.form.fields.name)
            formdata.append('email_address', this.form.email_address)
            formdata.append('message', this.form.fields.message)
            axios.defaults.xsrfCookieName = 'csrftoken'
            axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
            axios.post('/', formdata)
                .then((response) => {
                    if (response.data.status !== 200){
                        this.form.errors.set(response.data.errors)
                        console.log(window['vue-toastify'])
                    } else {

                    }
            })
        }
    },
})

I would like to show a toast at the response. This is in a single file with a couple of classes for form and form errors, and vue dev tools are the only thing that is enabled.


Solution

  • In your case you cannot use .vue file instead you can just use .js file.

    Since VueToastify export the module as a plugin (some libraries might export as a component you can indicate it from exported object, for plugin it will have install function). So you have to install it first.

    Vue.use(window['vue-toastify'].default)
    

    Then you just call it when you want to use.

    this.$vToastify.success('some-text')
    

    Example