What is the best way to transfer parameters from the Vue root to a component?

Currently, I am attempting to transfer a string value from index.cshtml to the main Vue element.

The specific parameter I want to pass is: userId

Location: Index.cshtml (this is where the parameter is obtained)

@using Microsoft.AspNetCore.Identity
@inject SignInManager<User> SignInManager
@using LaBouteilleDamour.Domain.Models;
@inject UserManager<User> UserManager

@if (SignInManager.IsSignedIn(User))
{
    User user = await UserManager.GetUserAsync(User);
    var userid = UserManager.GetUserId(User);

    <div id="cartApp" userId:"userid"></div>
    <script src="./js/Cart.bundle.js" asp-append-version="true"></script>
}

Main Vue Element: Cart.boot.ts

import Vue from "vue";
import Cart from "./Components/Cart.vue";

new Vue({
    el: "#cartApp",
    template: '<Cart :userId="userId" />',
    props: {
    *userId: String,
    },
    components: {
        Cart
    }
});

Vue Component: Cart.vue (where the parameter is needed)

<template>
 /*HTML*/
</template>

<script lang="ts">
    import ShoppingCartItem from "../Components/ShoppingCartItem.vue";
    import ShoppingCartService, { ICartItem } from "./AP
/ShoppingCartService";
    import Vue from "vue";


    interface IShoppingCartpageData {
        items: ICartItem[],

    }

    export default Vue.extend({
        data(): IShoppingCartpageData {
            return {
                items: [],
            }
        },
        props: {
            userId: {
                type: String,
                required:true,
            }
        },
        ...
    })
</script>

Answer №1

Make sure to define the "userId" in your Vue data function so it can be reactive and accessible in the DOM of your template.

The root view does not need props, as props are for receiving data from parent components only.

To fix this, modify your code for the root element like this:

import Vue from "vue";
import Cart from "./Components/Cart.vue";

new Vue({
    el: "#cartApp",
    template: '<Cart :userId="userId" />',
    data: function(){
      return {
        userId: userid, // Accessing userId from global scope where it is defined.
      }
    },
    components: {
        Cart
    }
});

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

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

the drawbacks of using mixins as outlined in Vue's official documentation

The documentation mentions a downside to mixins in Vue 2. One limitation is reusability: as parameters cannot be passed to the mixin in order to change its logic, their flexibility in abstracting logic is reduced. I'm struggling to fully grasp this ...

Deleting a segment of content from a webpage

Currently, I'm in the final stages of completing a blackjack game. However, one aspect that I haven't implemented yet is the ability for the user to play again after finishing a round. My initial idea is to use a window.confirm dialog box, where ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

Creating reactivity in Vue 3 prop objects: A step-by-step guide

I recently encountered this code snippet in a VueMastery tutorial, but it seems to be outdated: export default { setup(props, {emit}){ let email = props.email; let toggleRead = () => { email.read = !email.read axios.put(`http://loc ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...

Next.js data response not found

My code seems to be having an issue where the data fetched is not displaying on my website. I can see the data when using console.log(data), but nothing shows up when using src={data.img1}. async function getData() { const res = await fetch("http:/ ...

Tips for displaying "onclick" content beside dynamically generated content

I am working on a feature where a dynamically generated list has radio buttons displayed next to it. The goal is to show a dropdown list next to the specific radio button and list item that was changed. Essentially, if the radio button is set to "yes," I w ...

Why does my MEVN application only display the back end when I try to deploy it on Heroku?

I am encountering an issue with my app deployment on Heroku where the backend server is being displayed instead of my Vue app. Despite having an if statement in app.js that serves the files only in production, removing the if statement did not resolve the ...

JavaScript-generated div not recognizing CSS in Internet Explorer

Once again, dealing with Internet Explorer has become a major headache. On headset.no, we have incorporated a small blue search field. However, when you input "jabra" into the field, it should generate suggestions in a div underneath. This feature operates ...

What is the best way to interpret the JavaScript code within a Vue/Quasar project?

Sample Code: <script type="text/javascript" src="https://widget.example.com/widgets/<example_id>.js" async defer></script> I am looking to integrate this code into Quasar Framework and utilize it with Vue.js. Do you have any suggesti ...

Effortless 'rotational' script

I am currently developing a HTML5 Canvas game with the help of JavaScript. My aim is to create an object that smoothly transitions to a specific direction. The direction is being stored as a variable and calculated in radians. Here's how the code op ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

The process of filtering and outputting JSON data in JavaScript or jQuery

There is JSON data available for review. var data = [{ "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { ...

Implementing Image Data in AngularJS: A Guide to Binding Images to IMG Tags

Allow me to explain the problem further. I am retrieving a user's profile picture by calling an API that returns image data, as shown in the screenshot below https://i.stack.imgur.com/t8Jtz.jpg https://i.stack.imgur.com/pxTUS.png The reason I canno ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...

Steps for incorporating 'admin-ajax.php' on the frontend

Here is the code for Javascript. Javascript used: new AjaxUpload('#upload_btn', { action: '<?php echo admin_url("admin-ajax.php"); ?>', This function only functions when the user is logged in. ...

Using jQuery Accordion within the MVC Framework

I'm new to MVC and considering using an accordion. However, I'm facing issues as the accordion does not appear despite adding all necessary references for jquery accordion and creating the div. Here is my code: @{ ViewBag.Title = "Online Co ...

Encountering a "Evaluation Failed" error while scraping YouTube data with Puppeteer and Node.js

As I attempt to scrape the YouTube headline and link from a channel using Puppeteer, I encounter an Evaluation Error presenting the following message: Error: Evaluation failed: TypeError: Cannot read properties of null (reading 'innerText') a ...