npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-models

v1.4.9

Published

A better model plugin for Vue.js

Downloads

36

Readme

vue-models

Version Build Coverage Status License: MIT

A better models plugin for Vue.js

Installation

npm install vue-models

Demo

Clone the repository and run npm start or view a live demo here.

Setup

import Vue from 'vue'
import VueModels from 'vue-models'

Vue.use(VueModels)

Models

The Model class returns a Vue instance with some default helper methods and computed properties. The following is an example of extending the Model class:

import { Model } from 'vue-models'

export class User extends Model {
  static defaults() {
    return {
      name: 'user',
      computed: {
        full_name() {
          return `${this.first_name} ${this.last_name}`
        }
      }
    }
  }
  static schema() {
    return {
      first_name: {
        type: String
      },
      last_name: {
        type: String
      }
    }
  }
}
import UserModel from './models/user'

const user = new UserModel({
  first_name: 'Jane',
  last_name: 'Doe'
})

console.log(user.full_name) // returns 'Jane Doe'

Computed Properties

The Model class has some default methods and computed attributes that are useful for basic CRUD operations, but can be overrided by passing options to the constructor:

Model.basePath

An overwriteable property that defaults to the name of the model (with rudimentary pluralization). To override the default value, either pass a new one as a computed property, or in the root level of the options.

For a custom static basePath:

import { Model } from 'vue-models'

export class Property extends Model {
  static defaults() {
    return {
      name: 'property',
      basePath: 'properties'
    }
  },
  static schema() {
    return {}
  }
}

Or a computed basePath:

import { Model } from 'vue-models'

export class User extends Model {
  static defaults() {
    return {
      name: 'user',
      computed: {
        basePath() {
          return `${this.role}s`
        }
      }
    }
  }
  static schema() {
    return {
      role: {
        type: String
      }
    }
  }
}

Model.urlRoot

A computed property that defaults to ${basePath}/${id}, (ie. /users/12345678). This will be used for all CRUD operations except create, which will not have access to an id.

Model.url

Returns either the basePath if the model is new, or the urlRoot if the model already has an id. This is used for all CRUD operations. If overrided, this property will be used for all CRUD operations.

Model.isNew

Based on whether or not the model has an id. Affects whether or not Model.save is a POST or PUT.

Methods

Model.fetch()

Fetches the model via a GET at Model.url

Model.save(data, options)

Data must be valid json, options may contain a path property in order to deviate from the standard urlRoot.

Model.destroy()

Sends a DELETE request for the model.

Model.reset()

Uses the schema definition to reset all values to their default values.

Model.toJSON()

Returns all approved data attributes, in addition to all computed properties as json.

Binding to Vue components

Models can be bound to a Vue component using the following syntax:

export default {
  models: {
    user() {
      return new UserModel(data)
    }
  },
  created() {
    console.log(this.$user.full_name);
  }
}

NOTE: By default, models are reset when the parent component is destroyed. To disable this, the persist: true option can be provided in the model options.

Schema

Model classes use a static schema method to defined the initial data properties for the Vue instance. The schema format is heavily influenced by JSON Schema, with few differences. JSON Schema is frequently used for validation, while vue-models uses a schema to define initial state, and to transform data. Data can be transformed by creating custom type classes that mimic the behavior of the native constructors. Run the demo for a comprehensive example of data transformation that handles extended JSON ObjectIds and ISODates.

The following is an example of some nested structures in a schema definition. It should look familar to those who have used JSON Schema.

import { Model } from 'vue-models'

export class User extends Model {
  static defaults() {
    return {
      name: 'user'
    }
  }
  static schema() {
    return {
      preferences: {
        type: Object,
        properties: {
          notifications: {
            type: Object,
            properties: {
              email: {
                type: Boolean
              },
              text: {
                type: Boolean
              }
            }
          },
          privacy: {
            type: Object,
            properties: {
              sendBugReports: {
                type: Boolean,
                default: true
              }
            }
          }
        }
      },
      friends: {
        type: Array,
        items: {
          type: Object,
          properties: {
            id: {
              type: String
            }
          }
        }
      }
    }
  }
}

NOTE: By default, vue-models will print warnings in the console is data is set on a model without a matching schema definition. This is particularly important for root-level keys, which Vue will not be able to make reactive. To disable these warnings, pass schemaWarnings: false as an option when initting the plugin with Vue.

import Vue from 'vue'
import VueModels from 'vue-models'

Vue.use(VueModels, {
  schemaWarnings: false
})

Types

Below is an example of creating a custom type for converting MongoDB entended json ISODates to friendlier locale strings. The MongoDB date key $date is passed to the parent class, Type, so that the ISODate class knows where to look for the value. The in method defined how the data should be validated and processed before setting the state, and the out method defines how the data should be transformed before encoding or saving the model.

import { Type } from 'vue-models'

export class ISODate extends Type {
  constructor(value) {
    super(value, '$date')
    return this
  }
  in(value) {
    const parsed = new Date(value)
    if (!isNaN(parsed.getTime())) {
      this.value = value
    } else {
      throw new TypeError(`Invalid date: "${value}"`)
    }
  }
  out() {
    return this.value
      ? new Date(this.value).toLocaleString()
      : undefined
  }
}

Requests

This plugin uses the vue-requests plugin, which is a wrapper around the fetch API and includes the whatwg-fetch polyfill.

Build Setup

# install dependencies
npm install

# serve demo at localhost:8080
npm start

# run tests with jest
npm test

For detailed explanation on how things work, checkout the guide and docs for vue-loader.