Leveraging Vue js components while utilizing it from a content delivery network (CDN

I'm attempting to utilize the ButtonCounter component as a demonstration (source: https://vuejs.org/guide/essentials/component-basics.html#defining-a-component), but I am facing difficulties in getting it to function properly. I am utilizing Vue.js 3 from a CDN.

Here is the content of my ButtonCounter.js file:

export default {
  data() {
    return {
      count: 0
    }
  },
  template: `
    <button @click="count++">
      You have clicked me {{ count }} times.
    </button>`
}

Next, I have the main JavaScript file with Vue:

import ButtonCounter from './ButtonCounter.js'


const app = Vue.createApp({
  components: {
    ButtonCounter
  },

  data() {
    return {
      aaa: []
    }
  },
  methods: {
    ...
  }
}
})

app.mount('#app')

Lastly, within the HTML document where I link Vue.js from the CDN, and specify the following inside the body:

<ButtonCounter />

Despite following these steps, I am unable to see the button. Could someone please advise me on what I might be doing wrong?

Answer №1

After struggling for a bit, I finally cracked the code with the help of the vue-loader project. If you're interested, check out https://github.com/FranckFreiburger/vue3-sfc-loader. It's an amazing resource!

index.html:

  <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ee8ebfbadb3edf8fdb3f2f1fffafbecdeaeb0a6b0aa">[email protected]</a>/dist/vue3-sfc-loader.js"></script>

<div id="app">
  ....
  <ButtonCounter />
</div>

<script src="/main.js"></script>

main.js:

const { loadModule } = window['vue3-sfc-loader'];

const VueLoaderOpts = {
  moduleCache: { vue: Vue },
  async getFile(url) {
    const res = await fetch(url)
    if(!res.ok)
       throw Object.assign(new Error(url+' '+res.statusText), { res });
    return await res.text();
  },
  addStyle: () => {},
}

const app = Vue.createApp({
  components: {
    'ButtonCounter': Vue.defineAsyncComponent(() => loadModule('./ButtonCounter.vue', VueLoaderOpts))
  },

  data() {
    ...
  }
}

ButtonCounter.vue:

<script>
export default {
  data() {
    return {
      count: 0
    }
  }
}
</script>

<template>
  <button @click="count++">
    You clicked me {{ count }} times yet.
  </button>
</template>

Answer №2

When you mount your Vue application, anything inside the <div id=app></div> in the index.html gets overwritten.

To ensure it works properly, place your code inside the template of your main.js file:

import ButtonCounter from './ButtonCounter.js'
const app = Vue.createApp({
    components: {
        ButtonCounter
    },
    template: `<ButtonCounter />`
})

app.mount('#app')

Remember, if you forget to add type=module on the script tag for your main.js, it will cause issues when you try to import.

Answer №3

For those working with Vue 3, here's a helpful tip - you can utilize SFC with the assistance of a handy tool provided in this particular package

When setting up Vue in your script, consider using it in the following manner:

app.js

 // Setting up vue-sfc-loader
const options = {
    moduleCache: {
        vue: Vue,
    },
    async getFile(url) {
        const res = await fetch(url);
        if (!res.ok)
            throw Object.assign(new Error(res.statusText + " " + url), { res });
        return {
            getContentData: (asBinary) =>
                asBinary ? res.arrayBuffer() : res.text(),
        };
    },
    addStyle(textContent) {
        const style = Object.assign(document.createElement("style"), {
            textContent,
        });
        const ref = document.head.getElementsByTagName("style")[0] || null;
        document.head.insertBefore(style, ref);
    },
};

const { loadModule } = window["vue3-sfc-loader"];
// END Setup vue-sfc-loader

const base_component_url = '/static/assets/dashboard/js/vue/';

function load(path) {
    return Vue.defineAsyncComponent(() => loadModule(base_component_url + path, options))
}

const app = Vue.createApp({ 
    delimiters: ['[[', ']]'], 
    components: {
        'Greeting': load('components/test/Greeting.vue')
    }
});

app.mount('#__VUE');

To include the component in your HTML, do so like this:

<Greeting></Greeting>

or

<Greeting />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

Once the image has been observed, what steps can be taken to close it?

I wish to implement a functionality where clicking on the view button will enlarge the image, and another click on the page will return it to its original size. import * as React from 'react'; import Box from '@mui/material/Box'; imp ...

An error of type TypeError occurred while attempting to browserify a module in a Node.js environment

Is there a way to integrate this algorithm into a client-side function? I'm looking to use the RAKE Module within a browserified function on the client side. You can find the RAKE Module on GitHub here: https://github.com/waseem18/node-rake To compi ...

The code for the bouncing image isn't functioning properly outside of the JSFiddle environment

I'm having issues with this jQuery snippet in my web application. It works fine on jsfiddle, but not when I add it to my project. Here's the code: $('.myimage').mouseenter(function() { $(this).effect('bounce',500); }); Her ...

Enhance your browsing experience with a JavaScript bookmarklet that allows you to easily search through

Struggling to develop a JS Bookmarklet that scans the source code of the current page for a specific code like "G1_Value_client." If found, I need it to trigger alert A; if not found, trigger alert B. Seeking assistance as I am facing some challenges with ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

Tips for sending an HTML form through Ajax, storing the data in a file, and then showcasing the results in a div

Embarking on my journey in Web Development, I am currently delving into JavaScript (specifically JQuery) and have decided to kick things off with a Simple Chat project. However, I'm facing an issue with preventing the page from refreshing after a mess ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

Determine the height of the left div, which is set to auto, and apply the same height to the right div, which has overflow set

I am facing an issue that needs a solution. I need to ensure that two div elements have the same height. The left div should have 'auto' height while the right one must match it. Moreover, the right div contains 14 nested divs that need to be scr ...

Guide on incorporating d3 axis labels within <a> elements?

Issue at Hand: I am working with a specific scale var y = d3.scalePoint().domain(['a','b','c']).range([0,100]); I have successfully created an axis for this scale var y_axis = svg.append("g").attr("class", "axis").call(d3. ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Personalize the menu item in material ui

Currently, I have a <select> component from Material UI and I am iterating over the menuItem elements. Here is a sample you can reference: here My issue lies in trying to change the background color of each menu item. Although I attempted to do so, ...

Steer your keyboard attention towards the parent element that embodies a list

My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events. The goal of keyboard accessibility includes: Tab key to navigate the menu elements. Pressing the down arrow key opens a focused menu. ...

Check for non-null Sequelize Where conditions

Suppose I need to execute a select command using Sequelize with the condition: WHERE ID=2134 However, if the user does not provide an ID, then the WHERE clause should be omitted (as it is null). What is the best way to handle this situation in Sequelize ...

Retrieve information from an API and populate a MDBootstrap datatable using Vue.js and Axios

I am looking to populate a mdbootstrap datatable with data from my API. Is there a way for me to create a method that can call the getPosts() API and then write the results into the rows[] array? <template> <mdb-datatable :data="dat ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...