Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vue.js - Passing props to Vue root instance via attributes on element the app is mounted on

I am terribly new to Vue, so forgive me if my terminology is off. I have a .NET Core MVC project with small, separate vue pages. On my current page, I return a view from the controller that just has:

@model long;

<div id="faq-category" v-bind:faqCategoryId="@Model"></div>

@section Scripts {
    <script src="~/scripts/js/faqCategory.js"></script>
}

Where I send in the id of the item this page will go grab and create the edit form for. faqCategory.js is the compiled vue app. I need to pass in the long parameter to the vue app on initialization, so it can go fetch the full object. I mount it with a main.ts like:

import { createApp } from 'vue'
import FaqCategoryPage from './FaqCategoryPage.vue'

createApp(FaqCategoryPage)
    .mount('#faq-category');

How can I get my faqCategoryId into my vue app to kick off the initialization and load the object? My v-bind attempt seems to not work - I have a @Prop(Number) readonly faqCategoryId: number = 0; on the vue component, but it is always 0.

My FaqCategoryPAge.vue script is simply:

<script lang="ts">

    import { Options, Vue } from "vue-class-component";
    import { Prop } from 'vue-property-decorator'
    import Card from "@/Card.vue";
    import axios from "axios";
    import FaqCategory from "../shared/FaqCategory";

    @Options({
        components: {
            Card,
        },
    })
    export default class FaqCategoryPage extends Vue {
        @Prop(Number) readonly faqCategoryId: number = 0;

        mounted() {
            console.log(this.faqCategoryId);
        }
    }

</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems passing props to root instance vie attributes placed on element the app is mounting on is not supported

You can solve it using data- attributes easily

Vue 2

const mountEl = document.querySelector("#app");

new Vue({
  propsData: { ...mountEl.dataset },
  props: ["message"]
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" data-message="Hello from HTML">
  {{ message }}
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...