Enhancing HTML with VueJS and managing imports

After successfully developing a Single Page Application using VueJS, I realized that the SEO performance was not up to par. To combat this, I decided to create a standard HTML website with some pages incorporating VueJS code (since my hosting environment doesn't support Node.js for server-side rendering).

I found guidance on integrating Vue.js into existing websites from this helpful guide

My search.js file holds all my VueJS instance and methods information

Vue.component('todo-component', {
    template: '#todo-component',
    data: function () {
        return {
            items: [
                {
                    id: 'item-1',
                    title: 'Checkout vue',
                    completed: false
                }, {
                    id: 'item-2',
                    title: 'Use this stuff!!',
                    completed: false
                }
            ],
            newItem: ''

        };
    },
    methods: {
        addItem: function () {
            if (this.newItem) {
                var item = {
                    id: Math.random(0, 10000),
                    title: this.newItem,
                    completed: false
                };

                this.items.push(item);
                this.newItem = '';
            }
        }
    }
});

var app = new Vue({
    el: '#vue-app'
});

However, I am facing difficulties in importing libraries such as axios and other components

Whenever I try to add an import statement like:

import axios from "axios";

I encounter an error - Uncaught SyntaxError: Unexpected identifier

I need assistance on where to properly place my imports within the script?

Answer №1

When working with code directly in the browser, it's easy to include the axios cdn in your html file before loading search.js:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

If you need to import components, you can find more information about component registration here. In general, if your components are registered globally using

Vue.component('my-component', {})
, you should be able to use them directly in your code.

Answer №2

Make sure to include the axios library in your project by adding the following script :

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Here is an example of how you can use axios in a browser environment :

new Vue({
  el: '#app',
  data: {
    dataReceived: '',
  },
  methods: {
    getData() {
      axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
        .then((response) => {
          this.dataReceived = response.data;
          console.log(this.dataReceived);
          return this.dataReceived;
        })
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0771726247352932293630">[email protected]</a>/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

</head>

<body>
  <div id="app">
    <button @click="getData" type="button">getData</button>
    <p>dataReceived: {{ dataReceived }}</p>
  </div>
</body>

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

Modifying worldwide variables within an ajax request

After spending considerable time attempting to achieve the desired outcome, I am faced with a challenge. My goal is to append the object from the initial ajax call after the second ajax call. However, it appears that the for loop is altering the value to ...

Unable to retrieve a response, the operation `users.findOne()` has exceeded the buffering time limit of 10000ms

I encountered an issue when attempting to make a POST login request. The frontend is deployed on Netlify here, and the backend is deployed on Heroku here. Here are my backend logs . I am receiving `users.findOne()` buffering timed out after 10000ms in ...

What could be causing an error when trying to use a computed property?

Currently utilizing Vuex. Within the Getter Foo function, I am returning two values within an array: return ["Try Again"] or return ["Data result", data]. In the computed property, I am checking the array length and returning based on ...

How to show multiline error messages in Materials-UI TextField

Currently, I am attempting to insert an error message into a textfield (utilizing materials UI) and I would like the error text to appear on multiple lines. Within my render method, I have the following: <TextField floatingLabelText={'Input Fi ...

Error: express is missing a closing parenthesis for the argument list

When running this code in the VS Code terminal, be sure to verify any errors that may occur. var express = require('express'); var app = express(); app.get('/', function(request, response) { response.send("hello world"); }); app.li ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

A guide to activating an input field based on the value of another input field in AngularJs

An AngularJs form requires the user to input the number of hours worked. If the value entered is 0, an additional question should be displayed for the reason why no work was done. <label>Hours worked:</label> <input ng-model="hours" type="n ...

New methods for Sequelize ES6 models do not currently exist

Encountering issues while using Sequelize JS v4 with ES6 classes, I'm facing difficulty with the execution of instance methods. Despite being defined in the code, these methods appear to be non-existent. For instance - Model File 'use strict&a ...

Is there a way to transform NextJS typescript files into an intermediate machine-readable format without having to build the entire project?

I need to deliver a Next.js project to my client, but I want to modify the TypeScript files so they are not easily readable by humans. The client will then build and deploy these files to their production environment. How can I achieve this? In summary, C ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

Fade in and out of div elements upon clicking on an # anchor

I have been attempting to create a function where different divs fade in and out when clicking on an image with an <a href>. Unfortunately, I have not been successful in getting it to work despite several attempts. Here is the code that I am using: ...

"Looking to log in with NextAuth's Google Login but can't find the Client Secret

I am attempting to create a login feature using Next Auth. All the necessary access data has been provided in a .env.local file. Below are the details: GOOGLE_CLIENT_ID=[this information should remain private].apps.googleusercontent.com GOOGLE_CLIENT_SECR ...

Cloning a table row through editing functionality in ReactJS

Hey there, I'm currently working on implementing an edit feature in react.js. The current functionality is such that when the edit button is clicked, it displays the row data in the name and email address fields. If submitted without any changes, it c ...

Notify of an Invalid CSRF Token within the Action Buttons Present in the Table

I've encountered a problem with the CSRF token when using a Handlebars each loop. I created a data table using the each loop but I'm unable to submit the delete button. The CSRF token only seems to work for submitting new data (POST) and updating ...

Video texture incorporated into Three.js

I'm currently experimenting with using a specific section of a video as a texture on a Three.js mesh. The video in question can be found at this link: . It features a fisheye lens, and I am only interested in incorporating the central circular portio ...

Instructions on utilizing module.exports to export an async function

I am facing an issue with returning the result of an async function to the route I am calling. How can I resolve this successfully? My goal is to export a token from file token_generator.js and display it on route ('/') using Express. The functi ...

I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function. Take a look at my ngOnInit method, ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...