Is there a way to save a Vue component separately from the HTML file when relying on a CDN for

Although the code is functioning properly, I am interested in storing my component outside of the HTML and then importing it. My preference would be to have it in a dedicated component folder. Is this feasible?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
</head>

<body>
    <div id="app">
        <test />
    </div>
    
    <script>
        const component1 = {
            template: `<div> <p>{{ item }}</p></div>`,
            props: ['prop'],
            data: () => ({ item: 'test' }),
        }

        const app = Vue.createApp({
            data: () => ({ someData: 'prop' }),
        })
        
        app.component('test', component1)
        app.mount('#app')
    </script>
</body>

</html>

Answer №1

Sure, it is possible to create a JavaScript file at a location such as `components/component1.js', containing the definition for your component.

const component1 = {
        template: `<div> <p>{{ item }}</p></div>`,
        props: ['prop'],
        data: () => ({ item: 'test' }),
    }

To use this file in your HTML document, simply import it with:

<script src="components/component1.js"></script>

Once imported, the component will be accessible within the script section of your document.

<script>
        const app = Vue.createApp({
            data: () => ({ someData: 'prop' }),
        })
        
        app.component('test', component1)
        app.mount('#app')
    </script>

Answer №2

Solution: Separate your component into its own file and import it using a script tag, just like you did with Vue.

Suggestion: It's common practice to bundle and package JavaScript code before deployment. Vite is one tool that can help with this process. Learn more about Vite here: https://vitejs.dev/

Answer №3

One way to handle this situation is to fetch the component as text and then evaluate it.

It's important to note that using eval can be risky and is generally not recommended.

Please keep in mind: This method assumes that you are not setting the object in the CDN resource. If that is the case, following Igor's suggestion to load it as JavaScript would be a better approach.

// Here we have a JavaScript object stored as text, retrieved from a CDN
const componentData = `{
  template: '<div> <p>{{ message }}</p></div>',
  props: ['prop'],
  data: () => ({ message: 'Hello World!' }),
}`;

// Simulating fetching data from CDN
const fetchData = () => Promise.resolve({
  text: () => componentData // Load the content as text?
});

// Using actual `fetch` instead
fetchData('https://example.com/component1.vue')
  .then(response => response.text())
  .then(dataText => eval(`(${dataText})`))
  .then(component => {
    const app = Vue.createApp({
      data: () => ({ propValue: 'some value' }),
    })
    app.component('test-component', component)
    app.mount('#app-root')
  });
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<div id="app-root">
  <test-component />
</div>

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

Is there a way to incorporate a callback function for animation in cgscenegraph?

After creating my animation, I am interested in incorporating a callback function when the loop of the animation comes to an end. Is there a way you can guide me on achieving this? Thank you. ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

When the form is submitted on the webpage, it refreshes to display the results

I have a simple HTML form and am using JavaScript to display the entered value to the webpage, but every time I hit submit the webpage reloads. I came across a similar issue discussed on Webpage reloading on submitting form, but the solution mentioned inv ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Come back and display JSX

I am encountering an issue with a function that is supposed to add JSX to the variable markup. However, when the function is called, the markup is displayed as plain text instead of JSX. How can I ensure that the string is rendered as JSX rather than plain ...

A jquery class for styling with CSS

I am looking to add a CSS class to a gridview. I attempted to use this style from a reference link, so I implemented the following code snippet: $(function () { $('[ID*=search_data]').on('click', function () { var fromda ...

The onclick function in the Navbar div fails to work for inner elements

Within my navbar, there is a .dropbtn div that I want to trigger a dropdown function when clicked. However, only the text "TOTAL" seems to activate this function onclick. The <span> and <i> elements inside the .dropbtn do not respond to clicks ...

Discovering the differences between input values in HTML when using scripts

I have a code snippet here for an HTML project. The code includes an input field for username and password. I am looking to compare the user's input with a specific value using JavaScript. My question is, what code should be included in the button cli ...

Merge text inputs to preview content prior to form submission

I've been on the hunt for a solution to display the collective values entered into multiple text box fields as they are being typed. Currently, I have 6 text boxes (description1, description2, description3, description4, description5, description6) wh ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

How to dynamically add style to an HTML element with v-for in Vue.js

Currently, I am dynamically adding elements to a list using v-for. <ol> <li v-for="light in lights"> <input type="range" min="0" max="255" v-model="light.currentBrightness" v-on:change="setBrightness(light)" /> </li> ...

Launching a Material-UI dialog box from a higher-level Header component

I have a setup where the header component is separate from the Register dialog modal component, functioning as parent and child components. My goal is to trigger the Register dialog (child) from the headerlink component (parent) Here is the code for my he ...

What are some techniques for handling the fetch API response within the confines of the useState hook?

I'm curious about what's going on here: After calling setFriend, I tried to log the friend variable but it showed up as an empty array. Can someone shed some light on this for me? :) import React, { useState } from 'react'; import But ...

Creating a visually appealing pie chart using data from a specific database field is simpler than you think!

In the table field, I have 3 categories: "not yet, currently, done". https://i.sstatic.net/bPXRz.png My goal is to create a pie chart. This is the model code snippet: public function select_by_status() { $sql = "SELECT COUNT(status_laporan) AS ...

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

Instructions for adding a unique custom external CSS link, such as Bootstrap CSS, to a specific REACT component

Is it possible to incorporate custom CSS from the Bootstrap website into a React component? Since this CSS file cannot be imported directly, what steps should I take to include it? <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap. ...

Implementing prerender-spa-plugin in Laravel Vue.js within the resources folder

I recently added the prerender-spa-plugin using npm to my Laravel application, which contains a Vue.js app within the resources directory. Can someone guide me on how to activate the prerender-spa-plugin in this setup? I've come across examples for st ...

How to launch a new window for a popup

How can I make IE8 open new windows as pop-ups without changing browser settings? I want to use JavaScript's window.open() function. Firefox opens new windows correctly, but IE8 opens them in tabs instead of pop-up windows. Any suggestions on how to a ...

Loop through an array with varying property sizes and apply individual styles to each corresponding div

I am working with an array of 50 squares, each with randomly generated side lengths. My goal is to loop through the array using ng-repeat and style each square uniquely based on its side length. Any suggestions? <div ng-controller="ShapesController as ...