简体   繁体   中英

How to pass parameter from Vue root to component?

i am trying to pass a string from index.cshtml to the vue root element.

the parameter i am trying to pass is: userId

View: Index.cshtml ( this is where i get my parameter )

@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>
}

Vue root: 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 i need the parameter to go )

<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>

You are passing "userId" in your template but userId is not defined in your vue's data function and hence is not reactive which means you cannot use it in DOM unless you declare it in data function.

Also root view does not require props, props should have only those element which the component is going to receive from the parent component.

So your code for root element must look something 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 as it is defined in Index.cshtml. } }, components: { Cart } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM