Search code examples
asp.net-mvcvue.jsrazor

How to pass data from a cshtml view to a Vue.js app then into a Vue component


Being new to Vue.js, I'm trying to pass data from a cshtml view to a Vue app, then from the Vue app to a Vue component within the app and render it there.

I'm trying to pass the data as data attribute within the target div that renders the Vue app:

The rendering div:

<div id="schoolsSearch" data-model-value="@Model.Title"></div>

Where the Vue app is initiated:

new Vue({
        el: '#schoolsSearch',
        data: {
            modelValue: document.getElementById('schoolsSearch').getAttribute('data-model-value').toString()
        },        render: h => h(schoolsSearchApp)
    });

Within the Vue app:

  data: function () {
            return {
                modelValue: null,

The component within the Vue app:

<School-Card  v-for="school in limitedItems" :passedvalue="modelValue"  :key="school.DisplayName" :school="school"></School-Card>

And within the component:

props: ['school'], passedValue: {
            type: String,
            required: true,
        }

<p>{{ passedValue }}</p>

There are no errors, if I view the Vue tools in Firefox I can see modelValue but it's null and hasn't been set to the value passed down from view to app.

What am I missing?


Solution

  • moving the data to the parent component should fix the issue

    {
      data: function () {
        return {
          modelValue: document.getElementById('schoolsSearch').getAttribute('data-model-value').toString()
        }
      }
    }