Convert Figma logo to code with AI

gothinkster logovue-realworld-example-app

An exemplary real-world application built with Vue.js, Vuex, axios and different other technologies. This is a good example to discover Vue for beginners.

4,064
1,296
4,064
102

Top Related Projects

Exemplary real world application built with React + Redux

Exemplary real world application built with Angular

ASP.NET Core backend implementation for RealWorld

Exemplary real world backend API built with Laravel

Example Spring codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

Quick Overview

The gothinkster/vue-realworld-example-app is a fully-fledged Vue.js application that implements the RealWorld specification. It serves as a demonstration of how to build a medium.com clone using Vue.js, showcasing best practices and modern development techniques. This project is part of the larger "RealWorld" initiative, which aims to create exemplary fullstack applications across various frameworks and platforms.

Pros

  • Provides a complete, production-ready Vue.js application structure
  • Implements a real-world scenario, making it an excellent learning resource
  • Follows Vue.js best practices and conventions
  • Integrates with a standardized backend API, allowing for easy comparison with other frontend frameworks

Cons

  • May be overwhelming for beginners due to its complexity
  • Requires understanding of advanced Vue.js concepts
  • Some dependencies might become outdated over time
  • Limited customization options as it adheres strictly to the RealWorld spec

Code Examples

  1. Vuex store module example:
import { TagsService } from "@/common/api.service";

export const state = {
  tags: []
};

export const actions = {
  async fetchTags({ commit }) {
    const { data } = await TagsService.get();
    commit("setTags", data.tags);
  }
};

export const mutations = {
  setTags(state, tags) {
    state.tags = tags;
  }
};

This code demonstrates how to set up a Vuex store module for managing tags in the application.

  1. Vue component example:
<template>
  <nav class="navbar navbar-light">
    <div class="container">
      <a class="navbar-brand" href="index.html">conduit</a>
      <ul class="nav navbar-nav pull-xs-right">
        <li class="nav-item">
          <router-link
            class="nav-link"
            active-class="active"
            exact
            :to="{ name: 'home' }"
          >
            Home
          </router-link>
        </li>
        <!-- More nav items -->
      </ul>
    </div>
  </nav>
</template>

<script>
export default {
  name: "RwvHeader"
};
</script>

This code shows a Vue component for the application's header, including navigation links.

  1. API service example:
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import { API_URL } from "@/common/config";

const ApiService = {
  init() {
    Vue.use(VueAxios, axios);
    Vue.axios.defaults.baseURL = API_URL;
  },

  setHeader() {
    Vue.axios.defaults.headers.common[
      "Authorization"
    ] = `Token ${JwtService.getToken()}`;
  },

  query(resource, params) {
    return Vue.axios.get(resource, params).catch(error => {
      throw new Error(`[RWV] ApiService ${error}`);
    });
  },

  // More methods...
};

export default ApiService;

This code demonstrates how to set up an API service using axios for making HTTP requests.

Getting Started

To get started with the Vue RealWorld Example App:

  1. Clone the repository:

    git clone https://github.com/gothinkster/vue-realworld-example-app.git
    
  2. Install dependencies:

    cd vue-realworld-example-app
    npm install
    
  3. Run the development server:

    npm run serve
    
  4. Open your browser and navigate to http://localhost:8080 to see the app running.

Competitor Comparisons

Exemplary real world application built with React + Redux

Pros of react-redux-realworld-example-app

  • Utilizes Redux for more robust state management
  • Larger community support and ecosystem for React and Redux
  • More comprehensive testing setup with Jest and Enzyme

Cons of react-redux-realworld-example-app

  • More complex setup and boilerplate code due to Redux integration
  • Steeper learning curve for developers new to React and Redux
  • Potentially slower initial render times compared to Vue

Code Comparison

react-redux-realworld-example-app (Redux action):

export const LOGIN = 'LOGIN';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILURE = 'LOGIN_FAILURE';

export const login = (email, password) => ({
  type: LOGIN,
  payload: agent.Auth.login(email, password)
});

vue-realworld-example-app (Vuex action):

login ({ commit }, credentials) {
  return new Promise(resolve => {
    commit(types.LOGIN)
    api.auth.login(credentials)
      .then(({ data }) => {
        commit(types.LOGIN_SUCCESS, data)
        resolve(data)
      })
      .catch(({ response }) => {
        commit(types.LOGIN_FAILURE, response.data.errors)
      })
  })
}

The React-Redux example uses a more explicit action creator pattern, while the Vue example leverages Vuex's simpler mutation-based approach. The Vue code is generally more concise, but the React-Redux code offers more flexibility in handling complex state changes.

Exemplary real world application built with Angular

Pros of angular-realworld-example-app

  • More mature ecosystem with robust tooling and extensive documentation
  • Strong typing with TypeScript integration out of the box
  • Dependency injection system for better code organization and testability

Cons of angular-realworld-example-app

  • Steeper learning curve due to more complex architecture
  • Larger bundle size, potentially impacting initial load times
  • More verbose syntax compared to Vue's simplicity

Code Comparison

Angular component example:

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html'
})
export class ArticleListComponent implements OnInit {
  articles: Article[];
  constructor(private articleService: ArticleService) {}
  ngOnInit() {
    this.articleService.getArticles().subscribe(articles => this.articles = articles);
  }
}

Vue component example:

<template>
  <div class="article-list">
    <article-preview v-for="article in articles" :key="article.slug" :article="article" />
  </div>
</template>

<script>
export default {
  name: 'ArticleList',
  data() {
    return { articles: [] }
  },
  created() {
    this.$store.dispatch('fetchArticles')
  }
}
</script>

The Angular example showcases its dependency injection and TypeScript integration, while the Vue example demonstrates its more concise syntax and template structure. Both implementations achieve similar functionality but with different approaches reflecting their respective framework philosophies.

Pros of node-express-realworld-example-app

  • Built with Node.js and Express, providing a robust and scalable backend solution
  • Implements RESTful API endpoints, making it easier to integrate with various frontend frameworks
  • Includes authentication and authorization features out of the box

Cons of node-express-realworld-example-app

  • Lacks a built-in frontend, requiring additional setup for a complete full-stack application
  • May have a steeper learning curve for developers not familiar with Node.js ecosystem
  • Requires more configuration and setup compared to the Vue-based alternative

Code Comparison

node-express-realworld-example-app:

router.post('/users/login', function(req, res, next){
  if(!req.body.user.email){
    return res.status(422).json({errors: {email: "can't be blank"}});
  }

  if(!req.body.user.password){
    return res.status(422).json({errors: {password: "can't be blank"}});
  }

vue-realworld-example-app:

<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">{{ title }}</h1>

The node-express example showcases backend route handling and input validation, while the Vue example demonstrates frontend template structure and component organization.

ASP.NET Core backend implementation for RealWorld

Pros of aspnetcore-realworld-example-app

  • Built on ASP.NET Core, offering robust server-side capabilities and scalability
  • Provides a more comprehensive backend implementation with database integration
  • Follows well-established design patterns and architectural principles for enterprise-level applications

Cons of aspnetcore-realworld-example-app

  • Steeper learning curve for developers not familiar with C# and .NET ecosystem
  • Less flexibility in frontend development compared to Vue.js-based applications
  • Potentially higher resource requirements for hosting and deployment

Code Comparison

aspnetcore-realworld-example-app (C#):

public async Task<IActionResult> Create([FromBody]ArticleCreateRequest request)
{
    var article = await _articleService.CreateArticle(User.GetUserIdFromToken(), request);
    return CreatedAtAction(nameof(Get), new { slug = article.Slug }, article.ToArticleResponse());
}

vue-realworld-example-app (JavaScript):

createArticle({ commit }, payload) {
  return ArticlesService.create(payload)
    .then(({ data }) => {
      commit(SET_ARTICLE, data.article);
      return data;
    });
}

The aspnetcore-realworld-example-app uses C# with async/await for handling article creation, while vue-realworld-example-app utilizes JavaScript with Promises for the same functionality. The ASP.NET Core version provides more structured error handling and input validation, whereas the Vue.js version offers a more concise and frontend-focused approach.

Exemplary real world backend API built with Laravel

Pros of laravel-realworld-example-app

  • Robust backend framework with built-in features for authentication, routing, and database management
  • Follows Laravel best practices and coding standards, making it easier for Laravel developers to understand and maintain
  • Includes comprehensive API documentation using API Blueprint

Cons of laravel-realworld-example-app

  • Limited frontend functionality compared to vue-realworld-example-app
  • Requires more server-side resources and setup compared to the Vue.js implementation
  • Less flexibility in terms of frontend customization and interactivity

Code Comparison

laravel-realworld-example-app (Laravel):

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        return $this->respondWithToken(Auth::user()->generateToken());
    }
    return response()->json(['error' => 'Unauthorized'], 401);
}

vue-realworld-example-app (Vue.js):

login({ commit }, credentials) {
  return new Promise((resolve, reject) => {
    ApiService.post("users/login", { user: credentials })
      .then(({ data }) => {
        commit(SET_AUTH, data.user);
        resolve(data);
      })
      .catch(({ response }) => {
        reject(response);
      });
  });
}

The Laravel example showcases server-side authentication logic, while the Vue.js example demonstrates client-side API interaction and state management. The Laravel code is more concise due to built-in authentication features, while the Vue.js code offers more flexibility in handling API responses and updating the application state.

Example Spring codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

Pros of spring-boot-realworld-example-app

  • Robust backend implementation using Spring Boot, offering better scalability and performance for large-scale applications
  • Provides a more comprehensive API structure with clear separation of concerns (controllers, services, repositories)
  • Includes built-in security features and database integration, making it easier to implement authentication and data persistence

Cons of spring-boot-realworld-example-app

  • Steeper learning curve for developers not familiar with Java and Spring ecosystem
  • Requires more setup and configuration compared to the Vue.js frontend-focused approach
  • Less flexibility in terms of frontend technology choices, as it's primarily focused on backend implementation

Code Comparison

spring-boot-realworld-example-app (Java):

@GetMapping("/articles/{slug}")
public ResponseEntity<SingleArticleResponse> getArticle(@PathVariable("slug") String slug) {
    return ResponseEntity.ok(
        SingleArticleResponse.builder()
            .article(articleQueryService.findBySlug(slug).orElseThrow(ResourceNotFoundException::new))
            .build()
    );
}

vue-realworld-example-app (JavaScript):

export const getArticle = slug => {
  return ApiService.get("articles", slug)
    .then(({ data }) => {
      return data.article;
    })
    .catch(error => {
      throw new Error(error);
    });
};

The spring-boot example showcases a more structured approach with annotations and clear error handling, while the vue example demonstrates a simpler, promise-based API call using a service layer.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

RealWorld Frontend JavaScript Style Guide


##New Maintainers wanted## Anyone up for the challenge of maintaining this repo? Reach out on twitter @vilsbole

RealWorld Example App

Vue.js codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API.

Project demo is available at https://vue-vuex-realworld.netlify.app/

This codebase was created to demonstrate a fully fledged fullstack application built with Vue.js including CRUD operations, authentication, routing, pagination, and more.

We've gone to great lengths to adhere to the Vue.js community styleguides & best practices.

For more information on how to this works with other frontends/backends, head over to the RealWorld repo.

Getting started

Before contributing please read the following:

  1. RealWorld guidelines for implementing a new framework,
  2. RealWorld frontend instructions
  3. Realworld API endpoints
  4. Vue.js styleguide. Priority A and B categories must be respected.
  5. Editorconfig setup. Most of the common editors support editorconfig by default (check the editorconfig download link for your ide), but editorconfig npm package have to installed globally for it to work,
# install editorconfig globally
> npm install -g editorconfig

The stack is built using vue-cli webpack so to get started all you have to do is:

# install dependencies
> yarn install
# serve with hot reload at localhost:8080
> yarn serve

Other commands available are:

# build for production with minification
yarn run build

# run unit tests
yarn test

To know

Current arbitrary choices are:

  • Vuex modules for store
  • Vue-axios for ajax requests
  • 'rwv' as prefix for components

These can be changed when the contributors reach a consensus.

FAQ

Where can I find the service worker file?

The service worker file is generated automatically. The implementation can be found under src/registerServiceWorker.js. You can find the dependencies implementation in this repo: yyx990803/register-service-worker.

Also, Google provided a good documentation on how to register a service worker: https://developers.google.com/web/fundamentals/primers/service-workers/registration

Vue.js Function API / Migration to Vue.js 3

Related resources:

Vue.js 3 will likely introduce breaking changes on how Vue.js applications will look like. For example, the Vue.js Function API might be introduced. This would cause a lot of our components to change in the overall structure. The changes would be minimal though. With the vue-function-api plugin, these changes could be applied already. The problem is that multiple integrations are not working with the plugin. There are intentions to make this work, but for the time being, we should rather focus on different areas. If you still want to be experimental with it, we are happy to get a Pull Request with some experimental feature implementations.

Connect

Join us on Discord