Allen Wang
Allen Wang

Reputation: 2502

vue.js how to pass data to root element

I'm currently building an application using a dotnet core backend and some Vue.js elements in the front. I was able to build the application using regular Vue (non template, plain non es6 javascript syntax) in a cshtml file, but I've been trying to move towards a more modular structure using vue components in .vue files.

The problem I'm running into is that in the original version, I would have access to Json objects when instantiating the root element:

var jsonRenderedWithHtml = @Html.Raw(Json.Serialize(Model.SomeJsonObject));

vm = new Vue({
        el: "#root-element",
        data: {
            vueData: jsonRenderedFromHtml;
        }, ...

When I switch over to the component version, from what I've found, I need to render the root element from a javascript file, doing something like this:

import RootElement from "../Vue/RootElement.vue";
import Vue from 'vue';

let vm = new Vue({
    el: '#root-element',
    render: h => h(RootElement)
});

Then, I would import this script in the @section Scripts part of the cshtml file. Unfortunately, from within the javascript file, there doesn't seem to be a way to pass in data from outside (from the cshtml file). It seems that if I were to instead write an AJAX request inside the vue root instance, it would need to do two server requests to do the same job.

It also seems that I can't use import statements within cshtml (don't seem to be any webpack loaders for cshtml?). Otherwise, I would skip rendering the element in a separate javascript file.

Upvotes: 2

Views: 2341

Answers (1)

Neal Cynkus
Neal Cynkus

Reputation: 64

What we did in our application was to output the data added to the ViewData into the view through as json into a script tag and added an object to the window in the script with the previously rendered json. In the beforeCreate we then read the data from the object we added to the window and commit it to our store. Something like:

    @{
    IHtmlString myObj = null;
    if(ViewData["SomeObject"] is ContentResult)
        myObj = Html.Raw(((ContentResult)ViewData["SomeObject"]).Content);

    <script type="text/javascript">
    (function(){
        window.obj = JSON.parse(myObj);
    });
    </script>

You could however add a prop to your App and pass the object in through the prop just create your vue instance in a script tag.

Upvotes: 1

Related Questions