Skip to content

Instantly share code, notes, and snippets.

@praveensewak
Last active August 1, 2020 06:10
Show Gist options
  • Save praveensewak/1ae82cbcc8305a1c0224ff9b3237fa1c to your computer and use it in GitHub Desktop.
Save praveensewak/1ae82cbcc8305a1c0224ff9b3237fa1c to your computer and use it in GitHub Desktop.

.NET Core 3.1 Web Application with NuxtJs

Microsoft.AsNetCore.SpaServices.Extensions

public void ConfigureServices(IServiceCollection services)
{
  services.AddSpaStaticFiles(options => { options.RootPath = "wwwroot"; });
  services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseRouting();

  app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

  app.UseSpaStaticFiles();
  app.UseSpa(builder =>
  {
    if (env.IsDevelopment())
    {
      builder.UseProxyToSpaDevelopmentServer("http://localhost:8080");
    }
  });
}

Nuxt Config

//nuxt.config.js
export default {
  buildDir: 'nuxt-dist'
}

Axios

// method inside template/component
axios
  .get("https://localhost:14500/api/users")
  .then(
    (response) => commit("loadUsersSuccess", response.data),
    (error) => commit("loadUsersError", error));

Vuex

// state.js
state: {
  globalNumber: 42,
  error: {
    loadUsers: ""
  },
  users: [],
  products: [{ name: "Default Product", price: 4.50 }],
},

// mutations.js
mutations: {
  loadUsersSuccess(state, data) {
    state.users = data;
  },
  loadUsersError(state, error) {
    state.error.loadUsers = error;
    state.globalNumber = -42;
  }
},

// actions.js
actions: {
  loadUsers({ commit }) {
    axios
      .get("https://localhost:14500/api/users")
      .then(
        (response) => commit("loadUsersSuccess", response.data),
        (error) => commit("loadUsersErrror", error));
  }
},

State usage

<template>
  <div class="container">
    <p>Global number is: {{ someNumber }}</p>
    <ul>
      <li v-for="u in users" :key="u.id">{{ u }} </li>
    </ul>
  </div>
</template>

<script>
  import {mapActions, mapState} from "vuex";
  
  export default {
    name: "HelloWorld",
    computed: {
      ...mapState({
        users: state => state.users,
        someNumber: state => state.globalNumber
      })
    },
    props: {
      msg: String
    },
    methods: {
      ...mapActions(["loadUsers"]),
      localLoad() {
        this.loadUsers();
      }
    }
  }
</script>

Controllers

[Route("api/user")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
  public async Task<IActionResult> Get()
  {
    // TODO: write your awesome code here
    return Ok();
  }
}

gitignore

[(https://www.toptal.com/developers/gitignore)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment