Importing template Vue files into Router in Vue.js

Hello everyone, I have a Vue.js project that I am working on and I am looking to import a vue template file into my index.html without using webpack or browserify.

It seems like I will need to use a router to accomplish this and include some additional JavaScript in my project.

<script src="https://unpkg.com/http-vue-loader"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

Within the script tag of my index.html, I am defining a new object that points to my navigation component that I want to include.

var Settings =  httpVueLoader('Navigation.vue') ,
router = new VueRouter({
    routes:[
        { path:'/navigation', component: Navigation }
    ]
});

I would like to simply use the

<navigation></navigation>
tags inside my index.html to display the content from the Navigation.vue file.

You can view my project on Codepen here: https://codepen.io/fennefoss/project/editor/ZerEod#

Answer №1

Opting for a module bundler is always advantageous for various reasons, with one of them being the ease of maintenance. In case that's not an option, consider registering the component in the script file as shown below:

Vue.component('navigation', {
  template: `
      <p>Click on the Menu Icon to transform it to "X":</p>
      <div v-bind:class="[ 'container', { 'change': active } ]" @click="myFunction">
        <div class="bar1"></div>
        <div class="bar2"></div>
        <div class="bar3"></div>
      </div>
    `, 
  data() {
    return {
      active: false
    }
  },
  methods: {
    myFunction(x) {
      this.active = !this.active;
      
      // add any additional logic here if necessary
    },
  },
})

const app = new Vue({
  el: '#app',
  data() {
    return {
      products: [],
      showMobileMenu: false,
      productHeadline: 'Product Flow Tool'
    }
  },
  computed: {
    totalProducts() {
      return this.products.reduce((sum, product) => {
        return sum + product.quantity
      }, 0)
    }
  },
  created() {
    fetch('https://www.fennefoss.dk/sample.json')
    //fetch('./sample.json')
    .then(response => response.json())
    .then(json => {
      this.products = json.products
    })
  },
})

index.html

<div id="app">
  <navigation></navigation>
</div>

You will still need to manage the CSS files appropriately, and this is where using a module bundler becomes beneficial—allowing you to utilize single file components.

Answer №2

There is no need for vue-router in this situation. Simply bring in the Navigation component with the following import statement:

import navigation from "./Navigation.vue"
Then, include it as <navigation/> in your HTML code.

Vue-router is utilized for managing different routes.

Answer №3

In order to properly set up Navigation.vue, make sure to export it accordingly. Also, remember to place your style and script tags outside the template section for better organization:

Navigation.vue:

<template id="navigation">
    <p>Click on the Menu Icon to transform it to "X":</p>
    <div class="container" onclick="myFunction(this)">
        <div class="bar1"></div>
        <div class="bar2"></div>
        <div class="bar3"></div>
    </div>

</template>

<style>
    .container {
        display: inline-block;
        cursor: pointer;
    }

    .bar1, .bar2, .bar3 {
        width: 35px;
        height: 5px;
        background-color: #333;
        margin: 6px 0;
        transition: 0.4s;
    }

    .change .bar1 {
        -webkit-transform: rotate(-45deg) translate(-9px, 6px);
        transform: rotate(-45deg) translate(-9px, 6px);
    }

    .change .bar2 {
        opacity: 0;
    }

    .change .bar3 {
        -webkit-transform: rotate(45deg) translate(-8px, -8px);
        transform: rotate(45deg) translate(-8px, -8px);
    }
</style>

<script>
    module.exports = {
        data: function () {
            return {};
        },
        mounted: function () {
            function myFunction(x) {
                x.classList.toggle("change");
            }
        }
    };
</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

Elements overlapped with varying opacities and responsive to mouse hovering

In this Q/A session, we will explore a JS solution for managing the opacity of overlapping elements consistently during hover. Objective Our goal is to create two transparent and overlapping elements, similar to the red boxes showcased below. These eleme ...

How can we prevent dispatching within a dispatch in React Flux?

It seems that I have come across a situation where I am struggling to avoid the dispatch-within-a-dispatch problem in Flux. While I have found similar questions addressing this issue, none of the solutions provided seem to be ideal, as they often involve ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

Why is it that the form consistently comes back as invalid?

I populated my edit form inputs with data from an API response, https://i.sstatic.net/2HUpr.png When I click on Continue, the validate() function is triggered. validate() { this.$refs.form.validate() console.log('this.$refs.form.va ...

Tips on Moving a Bootstrap Modal Popup with the Arrow Keys on Your Keyboard

This example showcases the integration of Bootstrap's Default Modal Popup with jQuery UI Draggable Function. The JS fiddle link provided below contains the code snippet. $(document).ready(function() { $("#btnTest").click(function() { $(&a ...

Exploring the wonders of ReactJs in the ComponentDidMount

I am encountering some issues with my app. Although I am not a Javascript expert, it seems like an easy fix to me. I need to make the following call: this.props.onNavStyleChange(NAV_STYLE_FIXED); to change the navigation when this page loads. However, I ...

Angular input for date is showing wrong value due to timezone problem

My database stores dates in UTC format: this.eventItem.date: "2023-06-21T00:00:00.000Z" The input form field value is showing '2023-06-20' (incorrect day number), which seems to be a timezone issue. I am located in a region with a +3 o ...

Issues with the functionality of AngularJS routing system

angular.module('Stations', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/documents/:stationId', { templateUrl: '/Scripts/Modules/checklist/views/index.html', ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...

Creating a Nuxt 2 page that utilizes dynamic parameters

My link is constantly changing with the path /user/reset/{params1}/{params2}/{hash}/json. I have set up a page at /pages/user/reset/_slug.vue, but it only works with one parameter. What steps should I take to create a page that supports this entire path? ...

Retrieve the request body within the validation function of express-validator version 4

Recently, I began using express.js along with express-validator to validate input data. However, I have encountered a problem when trying to access the request body in the new check API introduced in version 4.0.0. In previous versions, it was simple to a ...

Encountered an issue during the package installation process in Next.js

PS E:\web dev 2024\threads> & npm install @clerk/nextjs @uploadthing/react mongoose svix uploadthing Unidentified symbol found in original text. At line:1 char:15 + & npm install <<<< @clerk/nextjs @uploadthing/react mongo ...

Javascript collapsible panel that is initially expanded

I found this code example here and decided to implement a collapsible panel using css/html/javascript: function toggleCollapsibleSectionWithAnimation() { this.classList.toggle("collapsible-active"); var buttonId = this.id; var sectionId = buttonId ...

How can I modify the content within a scoped `<style>` tag in Vue?

Is there a way to dynamically change the contents of a <style> block in my Vue component using Vue variables? Many commonly suggested solutions involve inline styles or accessing the .style property with JavaScript. However, I am looking for a metho ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Tips for sharing data between two components

In my project, I have a customized Shared Component which consists of an input search bar with a "continue" button. This Shared Component is being utilized within two other components - the buy component and sell component. The challenge I am encountering ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

steps for including preset text in an input field within a form on WordPress

I am currently utilizing a WordPress plugin that automatically generates a form in the admin area based on user input. The form includes five fields that require URL validation. Users have the option to enter optional link text which will be displayed as t ...