Search code examples
c#vue.jsrazor

Pass data to Vue.js component


I'm facing an issue with passing data to a vue component.

The .cshtml file looks like this:

@using Newtonsoft.Json;

@{
    var myString = "Hello world";
    var myJsonData = JsonConvert.SerializeObject(model);
}

<div id="gallery">
    <Gallery my-jsonprop="@myJsonData" 
             :my-jsonprop2="@myJsonData" 
             my-text="Hello world" 
             :my-text2="@myString" 
             v-bind:my-text3="@myString"></Gallery>
</div>

...and the Gallery.vue component something like this:

<template>
    <div>
        <p>{{ test }}</p>
        <p>{{ myJsonProp }}</p>
        <p>{{ myJsonProp2 }}</p>
        <p>{{ myText }}</p>
        <p>{{ myText2 }}</p>
        <p>{{ myText3 }}</p>
    </div>
</template>

<script>
    export default {
        name: 'Gallery',
        props: {
            myJsonprop: {
                type: Object,
                required: true
            },
            myJsonprop2: {
                type: Object,
                required: true
            },
            myText: {
                type: String,
                required: true
            },
            myText2: {
                type: String,
                required: true
            },
            myText3: {
                type: String,
                required: true
            }
        },
        computed: {
            test() {
                return "Foo bar"
            },
        }
    };
</script>

...and finally my main.js looks like this:

import Vue from "vue";
import Gallery from "../Gallery.vue"

new Vue({
    el: '#gallery',
    render: h => h(Gallery)
});

But neither of the properties is passed to the component, while the computed value of test is being displayed. Am I missing something?


Solution

  • So after excessive research, I've figured it out myself. It seemed that my webpack.config.js was missing on crucial thing for using single file components:

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".js", ".vue", ".json"],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': path.join(__dirname, "dist")
        }
    }
    

    This resolved it for me entirely!