Home » vue » Using Razor inside VueJs Component

Using Razor inside VueJs Component

Posted by: admin November 26, 2021 Leave a comment

Questions:

To avoid repeat re-writing the same code multiple times,I’m using VueJs component feature to make a component that includes the Select dropdown list.
The code goes like this

 Vue.component('select-component', {
        template: `
            <label>elType</label>
            <div class="col-md-colwidth">
            <select>
                <option value=""></option>
                @foreach (elType s in ViewBag.elTypes)
                {
                    <option value="@s[elType+"ID"]">@s["Designation"+elType]</option>
                }
            </select>
            <input type="hidden" v-model="elTarget">
            </div>
            `,
        props: {
            elType: {
                type: String,
                default: 'User'
            },
            elTarget: {
                type: String,
                default: 'user'
            },
            colwidth: {
                type: int,
                default: '3'},


        }
    })

As you can see, I’m requiring some data list I brought from the ViewBag
but all i get is that the Razor is always ignoring that it is inside a Vue Component and giving “The type or namespace name ‘elType’ could not be found “.

P.S:
1) the input Hidden is used in the original code to manipulate the bs jQuery select2

2)Don’t mind the elTarget and elType :p it’s actually same thing except I’m lazy to camelCase the word :p

3)I tried to wrap the inside @{ } but still toggle the same error

Answers:

You can’t use Razor ‘inside’ a Vue component because Razor generates the page server-side before Vue gets to do its stuff in the browser. What you have there is a Vue component inside a Razor page. elType is defined as a Vue prop, so it likely isn’t in your view bag?

In any case, please don’t do this! Use Razor or Vue. If you choose Vue, your vue components are static .js or .vue files, your data arrives via AJAX calls, and you loop through elTypes with v-for, in the browser. Any other way will lead to madness 🙂

###

You could send your razor with props to the component if necessary:

View file

<component-name :prop1="@Model.somethingOtherThanString" prop2="@Model.aString"></component-name>

Vue file

props: {
  prop1: Boolean,
  prop2: String
}