Creating Vue components and including Javascript code within them

Attempting to develop a component using Vue for my JavaScript code, but encountering issues. My primary aim is to build a component with either Vue or Vue3

    <head>
      <title></title>  
      <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    </head
    <body>

        <div id="app">
            <myelement name="ibrahim" age="12"></myelement>
        </div>

    </body>

    <script>
        Vue.component("myelement",{
            props:["name","age"], // for arguments 
            template:` 
            <h1> welcome to my vue component,<br> name :{{name }} and age : {{age}}</h1>
            
            `// template where my code template should be 
            
        })
        var vm = new Vue({ // creating an object from Vue
            el:"#app" // bind my created code to the id "app" 
        })
    </script>

While this code functions as intended, inserting JavaScript code instead of HTML code yields an error

The JavaScript code I am utilizing does not get invoked by Vue. Only the HTML code seems to execute.

    <head>
      <title></title>  
      <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    </head
    <body>
        <h3>this page works</h3>
        <div id="app">
            <myelement ></myelement >
        </div>
        
    </body>

    <script>
        document.write("<h1>Header from document.write()</h1>");

        const temp = "<h1>Hello from Vue variable</h1>";
        
        Vue.component("myelement ",{
            template:` 
                <script>
                    alert(1);
                    document.write("<h1>Header from document.write()</h1>");
                </script>

            `// template where my code template should be 
            
        })
        const vm = new Vue({ // creating an object from Vue
            el:"#app" // bind my created code to the id "app" 
        })
    </script>

The desired outcome is for the tag in the page to trigger an 'alert(1)' message.

Answer №1

Vue does not allow the use of script tags in template components, resulting in the following error:

[Vue warn]: Error compiling template: Templates should only handle state-to-UI mapping. Avoid using side-effect tags like <script> in your templates as they will not be parsed.

Instead, you can place your JavaScript code in the created lifecycle hook. This hook is triggered when your component is created:

<head>
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <h3>This page works</h3>
  <div id="app">
    <myelement></myelement>
  </div>
</body>

<script>
  Vue.component("myelement", {
    template: `<h2>Hello</h2>`,
  });
  var vm = new Vue({
    el: "#app",
    created() {
      alert(1);
      document.write("<h1>Header from document.write()</h1>");
    },
  });
</script>

Answer №2

I have a feeling that this code will function as intended:

<head>
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <h3>this page works</h3>
  <div id="app">
    <myelement :message="variableAtParent"></myelement>
  </div>
</body>

<script>
  Vue.component("myelement", {
    props: ['message'],
    template: '<p>At child-comp, using props in the template: {{ message }}</p>',,
  });
  var vm = new Vue({
    el: "#app",
    data: {
    variableAtParent: 'DATA FROM PARENT!'
    }
  });
</script>

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

Send an API request to update a table in a Vue.js application

I am currently learning about VUE and have a simple API request that provides information on bitcoin prices. I would like to update the table every second and am seeking the easiest way to achieve this. Below is the code snippet: async mounted() { const re ...

react-ga4 is sending multiple view events repeatedly

After setting up a Google Analytics account and creating a new property, I integrated the tracking ID with react-ga4 for my Album ItemPage as shown below: const ItemPage = () => { const {user} = useContext(AuthContext); let { item } = useParams ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

The method for triggering an event upon mounting in Vuejs

I have a sidebar displayed below: <template> <section> <div class="sidebar"> <router-link v-for="(element, index) in sidebar" :key="index" :to="{ name: routes[index ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

Encountering a issue when trying to click the Menu icon in a Vue 3 admin template

i recently set up the CoreUI Vue admin template CoreUI Vue Template. Everything seems to be working smoothly, except for the menu icon https://i.stack.imgur.com/tOShL.png. Whenever I try to hide the side bar (which is a built-in feature), it's not fu ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

"The webpack-dev-server seems to be failing to forward requests to an external domain using the proxy

I'm currently facing an issue with setting up the webpack-dev-server proxy configuration to route api requests to an external domain. Despite my efforts, I am unable to get it to function properly. Below is my configuration: var path = require(&apos ...

Using AJAX and React to handle RESTful requests

Hello there, I am attempting to utilize a web service in React but am encountering issues with the AJAX function. I'm unsure if my code is working as expected. Here is a snippet of my code: prox= {"email":email, "password": password}; //tag comment $ ...

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Can Vue Storefront Nuxt be seamlessly integrated with Algolia Search Routing in SSR for optimal performance?

Successfully integrated Algolia search with the VSF/Next branch, mastered the basics. Next up: tackling routing. While Vanilla Nuxt works smoothly with the integration, the number of workarounds is gradually increasing. To Reproduce: clone && yarn && ya ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

How can a "Loading" message be displayed while external JavaScript is loading?

I have mastered the art of using JS or jQuery to showcase a "Loading" message during the loading process. Currently, I am working on a sizeable web application that relies on various JS dependencies, and I am seeking a way to exhibit a "loading" message wh ...

The module script failed to load due to an unexpected response from the server, which was MIME type of text/jsx instead of a javascript module script

I have recently set up an express server and created an API, as well as installed React using Vite for my frontend. However, when I attempt to connect or load my main HTML file to the server, an error is displayed in the console. This is all new to me as I ...

Arrange a div close to another div with the help of absolute positioning

My goal is to create a tooltip-like positioning for an element within the same container as another element. When clicked, this particular element will display a div containing a table. You can find the complete code here: http://jsbin.com/xihebol When s ...

Can JavaScript be utilized to dynamically adjust the size of all elements on the screen to a specified percentage of their initial height and width when a certain event occurs?

I'm fairly new to the world of JavaScript, but I have a basic understanding of it. I want to optimize my personal website for mobile devices. I've already taken care of screen orientation and element positioning, everything is centered nicely and ...

Applying hover effect to material-ui IconButton component

As stated in the React Material-UI documentation, I have access to a prop called hoveredStyle: http://www.material-ui.com/#/components/icon-button I intend to utilize the IconButton for two specific purposes: Make use of its tooltip prop for improved ac ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...