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

Transforming an array of objects into individual objects using Vue.js and PHP

Is there a way to convert this object into an array of objects? [ [ { "fieldName": "4579043642", "message": "set number '4579043642' exists!" } ], [ { & ...

Error: React cannot read property 'any' since it is undefined

I am brand new to React and currently in the process of building a small app by following a tutorial on Udemy. The app includes a form, and while trying to import the redux-form library into my project, I encountered the following console error: https://i ...

Assign an array value to the input based on the selection made in Javascript

After finding a lot of useful information in previous questions, I am struggling to get the last piece that I need. My PHP code helps me loop through form fields and assign unique names to each field using a variable. One of these fields is for "expense ty ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Vue: function being called is not recognized within the inline-template component tag

I have a unique component that I am working with. It consists of various elements like modals, templates, and algolia search integration. <template> <div class="modal fade modal-primary" id="imageModal" tabindex="-1" role="dialog" aria-labelled ...

What is the best way to preserve the status of a report when moving to a new component instance?

In my Vue application, I am using Vue version 3.1.31 and vue-router version 4.0.14. Within the application, there is a report consisting of multiple objects that can navigate to a new route where users can view or print a PDF of the information. However, ...

Start the for loop to set up components using the data from the array

Trying to initialize custom elements (3 buttons) in a for loop but the first element is missing text. LeftMenu.vue <template> <div id="left-menu"> <MenuButton v-for="mytext in buttonList" v-bind:key="mytext" v-bind:mytext="mytext ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Guide on setting up a dynamic sidebar linked to the route in Nuxt.js

My pages folder is structured like this: pages/ --index/ ----page1/ ------_slug.vue ----page2/ ------_slug.vue ----page1.vue // contains different content ----page2.vue // contains different content --index.vue The routes can be accessed as follows: /i ...

Access a webpage in an html document using URL variables

In the process of developing an MVC web app without utilizing any MVC framework, I have created an index.html file with a section that dynamically loads all the views as needed by the user. However, I encountered an issue where direct URLs such as www.foo. ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Various array outcomes are produced by identical JavaScript (SAP UI5) code

Utilizing cachebuster to identify the modified file in the application structure. Javascript code snippet: https://i.sstatic.net/CZGfW.png Ineffective Array result: https://i.sstatic.net/D6MdS.png Effective Array result: https://i.sstatic.net/pQCIh.p ...

Nuxt.JS scss fails to load svg files

Every time I attempt to implement background-image: url(~/assets/svg/500.svg).... I encounter this error. My current setup involves using TailwindCSS alongside the PostCss module. Take a look at my package.json file here Also, feel free to check out my n ...

Tips for incorporating JSON data into an HTML table

https://i.sstatic.net/WEdge.jpgIn an attempt to showcase JSON data in an HTML table, I want the schoolClassName value to be displayed as a header (th) and the first names of students belonging to that specific schoolClass to appear in a column beneath the ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Is there a way to hide the <v-otp-input> field in a Vue.js application?

For more information, please visit https://www.npmjs.com/package/@bachdgvn/vue-otp-input <script> export default { name: 'App', methods: { handleOnComplete(value) { console.log('OTP completed: ', value); } ...

Using Django's template tag in conjunction with Vuetify's input value: a comprehensive guide

Is it possible to combine Django's template tag with Vuetify's input value? I found in Vuetify's documentation that the value can be set using the following method: Click here for more information <template> <v-form> < ...

Tips for extracting data from various select drop-down menus within a single webpage

As a newcomer to JQuery, I apologize if this question seems basic. I have a page with 20 categories, each offering a selection of products in a drop-down menu. The user will choose a product from each category, triggering an ajax call to retrieve the pric ...