Saturday, December 9, 2017

A little trick to create Vue.js single file reusable components without NPM and Webpack

I have started using VUE.JS to jazz up my front ends in Core MVC .NET and all I can say is WOW!

After cringing every time I had to use JQuery to make my page do things without a postback (Ajax) I kept looking for a solution.

Now don't get me wrong, I am no javascript or Node or NPM or ... expert. I barely even understand these technologies and especially how to make them work inside Visual Studio, so not everything in VUE works 100%.

Once I got the hang of Vue.js I quickly saw how COMPONENTS would be the key to creating reusable code. I especially like the idea of Single File Components, as they are self-contained and include the Template, Javascript, and CSS.

I am not creating SPAs, but load each CSHTML page like a normal .NET application. Inside the page is where the magic of Vue.js happens. I was disappointed when trying to use Single Page Components and realized I needed a bunch of additional things I didn't even understand (NPM, Webpack, ???, and ...). There seemed to be no end to items I had to add to Visual Studio, and all I wanted to do was add reusable Vue.js Components that I could include on certain pages.

So here is my trick, create Self-Contained CSHTML pages with the Vue.js Component and insert them in the page like a Partial View using @Html.Partial("vuejs-component.cshtml").

This worked for me, but if you have a better solution please let the community know.

The Vue.js Sample Code is here: https://vuejs.org/v2/examples/grid-component.html

And this is how I used it inside my CSHTML Page...

<div id="app">
<div>
<h3>{{test}}</h3>
</div>

<sob-grid :data="gridData"
:columns="gridColumns"
:filter-key="searchQuery">
</sob-grid>

</div>

@section Scripts {

@Html.Partial("~/vue/sob-grid.cshtml")

<script>

new Vue({
el: '#app',
data: {
test: 'Test Grid Component',
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
]
}
})

</script>

}

No comments:

Post a Comment