Set up ASP.NET Core 2.2 app with Vue JS on UI components without using npm/webpack.

Requirement

You got hired by WayKurat , a ficticios company that develops vue js/ ASP.NET Core apps.

The next day, you arrived late at the office. Your boss is waiting for you at your desk, he then cracks a smile when he noticed you approching. Luckily , he is not mad at you for being late, he is just excited to tell you that he wants you to develop a simple web app from scratch , the app will list down WayKurat Subscribers (The subscription web api is already developed by your annoying collegue).

You are requred to use ASP .NET Core 2.2 on VS 2017 and requested to try out libman instead of bower/npm or manually downloading libs.

Solution

Create a new ASP.NET Core application, set project name to WayKuratWeb.SimpleVueJs

Select ASPMVC Project Template

Your boss loves vue js so we will install Vue using Libman. Right click on project, then hit

Add -> Add Client-side library…

Libman add library window will show up, type in “vue” then click vue(will likely be a different version on your end) on dropdown list. Choose specific files, tick files as is on image below then hit install.

Now that vue is installed, lets make a vue component.
Create a new js file on wwwroot/js/
Set file name to VueSubscriberListComponent.js (just an example, you can call it like your grandma)

Next paste this js code . This will be our Vue component.Hide  

var subscriberListComponent = new Vue({
    el: '#subscriber-list-component',
    data: {
        subscribers: [],
        isViewReady: false
    },
    methods: {
        refreshData: function () {
            this.isViewReady = false;
            
            //dummy data for now, will update this later
            var subscribers = [
                { name: 'jic', email: 'paytercode@waykurat.com' },
                { name: 'kin', email: 'monsterart@waykurat.com' }
            ];

            this.subscribers = subscribers;
            this.isViewReady = true;
        }
    },
    created: function () {
        this.refreshData();
    }
});

Update project’s /Views/Home/Index.cshtml to reference vue and our componentHide   Copy Code

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <div id="subscriber-list-component">
        <h3>WayKurat Subscribers </h3>
        <div v-if="isViewReady == true">
            <ol>
                <li v-for="u in subscribers">
                    {{ u.name }} - {{u.email}}
                </li>
            </ol>
            <button class="btn btn-primary btn-block" v-on:click="refreshData">REFRESH</button>
        </div>
        <div v-else>
            <div>Loading data...</div>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/lib/vue/vue.js"></script>
    <script src="~/js/VueSubscriberListComponent.js"></script>
}

Run app on browser, your app will look like this. If not, check your browser console for errors(please check it before submitting a stackoverflow question, its not a black box)

Now time for us to consume your colleague’s web api.
But things are not as they seem to be, he did not pushed his code yesterday and looks like he is on AWOL.
So your forced to write a dummy web api for now.

Add a new controller, set name to SubscribersController.cs then paste this code.Hide 

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WayKuratWeb.SimpleVueJs.Controllers
{
    [Route("/api/[controller]/[action]/")]
    public class SubscribersController : Controller
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            //hard coded data for brevity, this must be from a data store on the real world
            var subs = new List<Subscriber>();
            subs.Add(new Subscriber() { Id=1,Name = "JEK",Email="jekhaxor@test.test"});
            subs.Add(new Subscriber() { Id = 1, Name = "Jikie", Email = "jekiedraws@test.test" });
            return Ok(subs);
        }
    }

    public class Subscriber
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

Now that the controller is added, will be consuming it on our component using ajax.
You are about to write a plain js sending XMLHttpRequest  but your boss smelled it and insisted to use axios.
Well if thats what he wants then let’s do it.

Install Axios via libman. Open up libman window like how we did while installing vue. Type in “axios” then select files as indicated on image below.

Add a reference to axios on Index.cshtmlHide 

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <div id="subscriber-list-component">
        <h3>WayKurat Subscribers </h3>
        <div v-if="isViewReady == true">
            <ol>
                <li v-for="u in subscribers">
                    {{ u.name }} - {{u.email}}
                </li>
            </ol>
            <button class="btn btn-primary btn-block" v-on:click="refreshData">REFRESH</button>
        </div>
        <div v-else>
            <div>Loading data...</div>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/lib/vue/vue.js"></script>
    <script src="~/lib/axios/axios.js"></script>
    <script src="~/js/VueSubscriberListComponent.js"></script>
}

Update VueSubscriberListComponent.js to consume our web apiHide   Copy Code

var subscriberListComponent = new Vue({
    el: '#subscriber-list-component',
    data() {
        return {
            subscribers: [],
            isViewReady: false
        };
    },
    methods: {
        refreshData: function () {
            var self = this;
            this.isViewReady = false;

            //UPDATED TO GET DATA FROM WEB API
            axios.get('/api/subscribers/getall/')
                .then(function (response) {
                    self.subscribers = response.data;
                    self.isViewReady = true;
                })
                .catch(function (error) {
                    alert("ERROR: " + (error.message|error));
                });
        }
    },
    created: function() {
        this.refreshData();
    }
});

You checked your app on the browser and things run as expected.You did your part, you’ve pushed your code to repo and prepared for lunch.
Now you’ve just used libman and wrote a vue compoenent.
Things will get complicated later but that will be next post.

External Reference

You’ll learn more here

https://vuejs.org/v2/guide/
https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-2.2

BÌNH LUẬN

Please enter your comment!
Please enter your name here