简体   繁体   English

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

[英]How to pass parameter from Vue root to component?

i am trying to pass a string from index.cshtml to the vue root element.我试图将一个字符串从 index.cshtml 传递给 vue 根元素。

the parameter i am trying to pass is: userId我试图传递的参数是:userId

View: Index.cshtml ( this is where i get my parameter )查看: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 root: Cart.boot.ts 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 Component: Cart.vue ( where i need the parameter to go ) 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>

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.您正在模板中传递“userId”,但 userId 未在 vue 的数据函数中定义,因此不是响应式的,这意味着您不能在 DOM 中使用它,除非您在数据函数中声明它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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