Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages:

<div id="contact-us" class="section md-padding bg-grey">
        <div id="contact"></div>

        <script src="/dist/build.js"></script>
</div>

Included in main.js is:

import Vue from 'vue'
import Contact from './Contact.vue'

new Vue({
    el: '#contact',
    render: h => h(Contact)
})

The Contact.vue file contains a template.

The goal is to determine which page the component was used on. To achieve this, a parameter needs to be passed from the div like

<div id="contact" page="main"></div>
. How can this be implemented?

Answer №1

How can I pass parameters from a div to a single page component in Vue.js?

It is not possible to directly pass parameters from a div since it is an HTML tag and not a custom component. You will need to create your own component that can accept the properties you want to pass.

To achieve this, first define your component and specify which properties it can receive. Then, use your component as demonstrated in the example below. For more information on passing props, refer to this documentation.

Vue.component('your-component', {
  props: ['property'],
  template: '<h3>{{ property }}</h3>'
})

new Vue({
  el: '#app'
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f090a1a3f4d514a514e49">[email protected]</a>/dist/vue.js"></script>

<div id="app">
  <your-component :property="'Hello props'" />
</div>

Example using Single File Component structure.

Parent component:

<template>
  <ChildComponent :property="propValue" />
</template>


<script>
  import childComponent from './childComponent.vue';

  export default {
    components: {
      ChildComponent: childComponent
    },
    data() {
      return {
        propValue: 'Hello prop'
      }
    }
  }

</script>

Children component:

<template>
  <h3>{{ property }}</h3>
</template>

<script>
export default {
  props: ['property'] // You can add more properties separeted by commas
}
</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

Creating a Command Line Interface (CLI) application in JavaScript for the browser: A guide to simulating blocking I/O

Developing a CLI application becomes quite simple with a blocking I/O API like PrintLn / ReadLn, making the process smooth and efficient. However, the challenge arises when trying to create a terminal application that runs on a browser using JS. In this s ...

Ajax is malfunctioning and failing to fulfill my needs

I cannot get Ajax to submit no matter what. I've been struggling for hours... script: <script> $(document).ready( $("#submit").click(function(e) { e.preventDefault(); $.ajax({ url: "https://maps.googleapis.com/maps/ ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

The Input element's onChange event is not functioning as expected

I am experiencing some issues with my code. I am trying to dynamically change the background color based on user input, but I am struggling to make it work. It seems like a simple task, so I must be missing something. Below is my HTML markup and jQuery: ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Reacting with Node.js: Capturing a selected option from a dropdown menu and storing it in the database

On my React frontend, I have a select dropdown like this: <select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option> ...

Displaying Keystonejs list items on every page

Is there a more effective method to efficiently load the content of a Keystone's list on every page, rather than calling it individually in each view? Could this be achieved through middleware.js? The objective is to create a dropdown for the navigat ...

Tips for Sending Props While Utilizing CSS Modules

I've been working with a button component that utilizes the Tailwindcss framework and css modules for some extra styling. It currently looks like this, incorporating template literal to integrate the red background styling. CSS Module: .red { back ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

What's the best way to adjust text color to black or white for maximum contrast when the background changes?

Currently, I am attempting to replicate the email element found on this website: .custom-blend-mode { mix-blend-mode: difference; } Although I have managed to make it work, it results in a change to the opposite color. Ideally, I would like it to remai ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Retrieve the HTML element by providing its specific index within the DOM structure of the document

I am working with the HTML source of a document stored as a string and have the index i which indicates where an element starts within this string. I am looking to create a function called getElementByIndex(i) that will return the appropriate JavaScript D ...

Ways to turn off hover highlighting

Is there a way to disable the highlighting effect of the <select> element in HTML? When you hover over items in the dropdown list, a blue color strip moves with your mouse. I need to find a way to get rid of this effect. Here is an example of the c ...

How can I completely alter the content of aaData in jquery.dataTables?

Looking to completely change the content of a datatable purely from a javascript perspective, without relying on Ajax calls. I've attempted using the following script: oTable.fnClearTable(); oTable.fnAddData(R); oTable.fnAdjustColumnSizin ...