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

JavaScript-generated buttons fail to trigger VueJS functions

I have a function that creates buttons for each item in a list, and each button is supposed to execute a function in the App.vue file when clicked. The issue I am facing is that neither the onclick nor the v-on:click methods are functioning as expected. ...

How to eliminate spacing between photos in a flexbox layout

[Unique] Find the Solution Image inside div has extra space below the image My design showcases various images of different sizes in multiple rows. See an example here. Despite my efforts, there are noticeable gaps between the rows that I can't seem ...

Managing State Changes with Redux

Reducers in Redux are primarily designed to be pure functions that take the previous state and an action as arguments, and return a new state object without mutating the previous state. However, it is still possible for developers to directly mutate the st ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

The Jquery .change() function refreshes the results just once

I am working on a form with 3 input fields named #first, #second, and #third, along with a fourth field labeled as #theResult. <div id="addFields"> <span id="addFieldsHeader">Add The Fields</span> <table style="margin:0 auto;"> ...

Utilizing React JS to assign various state values from a dropdown menu selection

In my project, I have implemented a dropdown list populated from an array of values. This dropdown is linked to a handleSelect function. const handleSelect = (e) => { handleShow() setCommunityName(e) } <DropdownButton id="dropdown-basi ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Infusing JavaScript with vibrant images

I am currently facing an issue where I am trying to insert images with JavaScript attached to them. Oddly enough, it seems to work fine on Firefox but the images or icons do not display on Internet Explorer. This is how I have written the code: <a hre ...

Step-by-step guide on accessing and displaying a disc file within a webix application

I am a beginner in webix development and struggling to find documentation or help for my current issue. Within my webix application, I am trying to create a button (let's call it 'View Report') that when clicked will open a file from my loc ...

Drawing a personalized cursor using JavaScript on a canvas

I've been working on creating a canvas that allows for drawing in vanilla JavaScript. Although I've successfully enabled drawing on the canvas, I'm now looking to implement a feature where a preview dot shows up when the user presses down be ...

Issue with AngularJS in Internet Explorer 7: "querySelector" property or method not supported by object

Incorporating angularjs into an existing asp.net project has presented a challenge due to the project's dependency on IE 7 compatibility mode. Upon running the project, an error from the angularjs file was encountered: Object doesn't support pro ...

AngularJS: Hide Row in NG-Grid Based on Condition

I am a beginner in angularJS and I have a requirement to hide a row in my ng-grid table if the value of a column is '0'. The grid consists of 4 columns: User Today This Week This Month I need to hide an entire row if the value in the 'Th ...

Tips for passing the name of a success function as a parameter in an AJAX request

My challenge is to create an AJAX call as a single function, where I pass the success function name as a parameter. Here's the function that I attempted: function MakeApiCall(dataText, apiName, functionName) { $.ajax({ url: apiUrl + apiName, ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Steer clear of Cross-Site Request Forgery through

As someone who is still learning about web security, I am curious about the best practices for using tokens on JavaScript requests to prevent CSRF attacks. Is it possible for someone to provide a code example? I already know how to implement this properly ...

Duplicate key error occurred in the collection resulting in Error Handling: E11000

Encountering an issue with the user model I'm utilizing alongside Mongoose and MongoDB to create profiles in my database. The process works smoothly when posting a single user, but throws an error upon logging out and attempting to add another: { ...

Change the chart.js labels every time I make changes to the chart

I've been using chart.js to generate dynamic charts. While I can create different types of charts and manipulate the data displayed, I'm struggling with updating the labels. Below is my code snippet showcasing how I update the data: const color ...

When using a variable to fetch data in JSON, an undefined error occurs. However, if a hardcoded index

I am facing an issue while trying to extract and manipulate JSON data from a file for an application I am developing. When looping through the data, I encounter an undefined error that seems to indicate a missing property in the JSON object when accessing ...

Combining two JSON objects using Angular's ng-repeat

My goal is to extract data from two JSON files and present it in a table: The first file 'names.json' contains: [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", ...

Tips for concealing a div using an article until it is activated by hovering over it

I am looking to incorporate a sleek sliding animation on an article that reveals more information in a div upon mouseover. A great example of this can be seen on where clicking at the top right corner triggers the "Show Modern Dev Ad" feature. Below is m ...