如何将参数从Vue根传递到组件?

时间:2019-04-22 09:37:36

标签: javascript vue.js asp.net-identity

我正在尝试将index.cshtml中的字符串传递给vue根元素。

我要传递的参数是:userId

查看:Index.cshtml(这是我获取参数的地方)

@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根: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组件:Cart.vue(我需要在其中输入参数)

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

1 个答案:

答案 0 :(得分:0)

您正在模板中传递“ userId”,但是在vue的数据函数中未定义userId,因此它不是被动的,这意味着您不能在DOM中使用它,除非在数据函数中声明它。

另外,根视图不需要props,props应该只包含组件将从父组件接收的那些元素。

因此您的root元素代码必须看起来像这样

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
    }
});