Giter Site home page Giter Site logo

xpepermint / vue-rawmodel Goto Github PK

View Code? Open in Web Editor NEW
80.0 4.0 7.0 1.39 MB

RawModel.js plugin for Vue.js v2. Form validation has never been easier!

JavaScript 17.23% Vue 30.94% TypeScript 51.83%
vue rawmodel model schema form validation reactivity debounce promise plugin

vue-rawmodel's Issues

Shared client and server side validation models

Thank you so much for sharing this great library!

Is it possible to share models between client and server? I'm working on a vue front end with a feathers/express back end where I want to have a single source of validation. In order to share models, should I just make a models folder in the project root directory (along side app and src directories which contain vue and feathers apps)? This project has a single package.json and webpack.config(s) at the project root directory.

I'm about to try this out. Can anyone provide any advice for getting this to work? I see that the vue-example has its models in the client src directory. Not sure if that app is doing server-side validation using those models. Is this the recommended method? I will post my results back here soon. Thank you.

Clarification of how to use nested schemas/models

I am having a little difficulty understanding how to properly use nested schemas. In the objectschema example I see that there is a nested schema (the field books has a type of [bookSchema]) in the user schema. I am clear on defining the schema but I am not sure how to use this operationally in vue.

For example if I have a form in the template which enables editing of the details of all books in addition to the user details.

  1. if I wish to have a button for adding additional books how do I code for this.
    e.g. my guess would be to use something like this.user.books.push({ title: 'True Detective' }), but this does not seem to work properly.

  2. I also am having some issue with v-model on the nested models.
    e.g. I am attempting to display fields for all the nested models. In terms of the user/book example it would be something like this for the first book in the array

{{ user.books[0].$title.errors | firstMessage }} I find that the user.books[0].title value of the model is not updated when I change the value in the form field (e.g. if I include {{ user.books[0].title value }} in the template to track this) and hence the rest of the methods/properties (e.g. hasErrors, errors) are not updated either. If I use a simple data object instead of the schema object this issue does not occur. I notice that when I change the value of a form field bound to a field such as user.name it triggers the user.books[0].title value to be updated such that it matches what is in the form field. Any insight into what I am doing wrong would be appreciated.

Decorator support

Allow for fields static method

http://aliolicode.com/2016/05/07/typescript-static-members/

https://github.com/xpepermint/vue-rawmodel/blob/master/src/models.ts#L29

public constructor (data: ReactiveModelRecipe = {}) {
    super(data);
    // ...
    let clazz = this.constructor;
    fields = fields || typeof clazz.fields === 'function' ? clazz.fields() : clazz.fields
    if (fields) this.defineFields(fields)
  }
import {ReactiveModel} from 'vue-rawmodel';

class User extends ReactiveModel {
  constructor (data = {}) {
    super(data); // initializing parent class
  }

  static fields() {
    return {
      name: {
        type: 'String', // setting type casting
        validate: [{
            validator: 'presence', // validator name
            message: 'is required' // validator error message
          }
        ]
      }
    };
  }
}

Equivalent to calling

  constructor (data = {}) {
    super(data); // initializing parent class
    this.defineField({
      // ...
    }
  }

Using Vuex

What's the best way to load in data from Vuex for a form? Everything from a getter is displaying an empty string that won't update when the data comes in.

Saving only changed and valid fields

I am looking to use vue-contextable to facilitate saving of only the fields that are both changed and valid. To do this I will need to:

  1. have an efficient method of querying whether any fields in the model are both changed and valid (e.g. to disable save button in a similar way to using hasErrors()). I was hoping to add a version of isChanged() which includes evaluation of isValid() in addition to whether the value has changed from the initial value.
  2. to extend the commit method of the model and fields to only commit fields that are valid and to return the names and values of only the fields that have been commited in a form that can be dispatched via a rest api for syncing changes with the database backend.

I had considered extending the ReactiveModel and Field classes and base the code for the new methods on the existing methods implemented (isChanged and commit). However, it is not clear to me how I would indicate for vue-contextable to use these extended classes instead of the existing classes. The other alternative is to define these new methods as instanceMethods on the Schema โ€“ I can see how this is done, but it would seem more complex to implement due to the need to handle nested models.

If you have any suggestions on the best approach to implement this functionality, I would appreciate the advice.

Example on loading data into model

Hi,

vue-contextable looks interesting - is it possible to get some guidance on best practice for loading/populating data into a model (e.g. json object returned from a get call to a web api). There appears to be a function 'populate(data)' defined for the document object in the objectschema package which may work but it does not seem to be available via this.{datakey}.$populate().

Any pointers would be appreciated.

Thanks,

Michael

Required if validator

One of the validators that I will need for my project is for a field to be required (non-blank) only when a condition is met based on the value of one or more other fields in the model. Currently, it does not appear that any of the built-in validators that will handle such a scenario - none appear to use values of another field as part of the validation. I intend to look at the code more closely to try to work out how to implement this but first I would like to check that it should be relatively simple to do this with the package. Another validator of interest is to validate that the value of the field is less/greater/equal to another field (e.g. dates).

Any insight into this would be appreciated.

Nested models and reactivity

I'm not quite sure if this is an issue with vue-rawmodel or Vue.js. but it seems that the support for nested models is limited or broken. Please see this demo for reference: https://codepan.net/gist/a7fe8b888cf6b5e92c84350e9ed22fbc

Basically I have two reactive models, where one model is a child of the other.

class MyModel extends ReactiveModel {
    name: string;
    locked: boolean;
    settings: Settings;

    public constructor({parent, ...data} = {}) {
        super({parent});

        this.defineField('name', { type: 'String', defaultValue: '' });
        this.defineField('locked', { type: 'Boolean', defaultValue: false });
        this.defineField('settings', { type: Settings, defaultValue: function() { return new Settings(); } });
    }
}

class Settings extends ReactiveModel {
    dummy: boolean;

    public constructor({parent, ...data} = {}) {
        super({parent});

        this.defineField('dummy', { type: 'Boolean', defaultValue: true });
    }
}

I have a custom form component named form-toggle looking like this:

Vue.component('form-toggle', {
  props: {
    value: { type: Boolean },
    onValue: { type: Boolean, default: true },
    offValue: { type: Boolean, default: false }
  },
  template: `<div>
    	<div class="toggle" :class="{on: isOn}">
        <div class="val" :class="{active: !isOn}" @click="turnItOff">off</div>
        <div class="val" :class="{active: isOn}" @click="turnItOn">on</div>
        <div class="marker"></div>
    	</div>
    </div>`,
  computed: {
    isOn: function() { return this.value === this.onValue }
  },
  methods: {
    turnItOn: function() { this.$emit('input', this.onValue); },
    turnItOff: function() { this.$emit('input', this.offValue); }
  }
});

And now we put it all together:

new Vue({
  el: "#app",
  data: {
    hasChanges: false,
    myModel: new MyModel()
  },
  computed: {
    status: function() { return this.hasChanges ? 'changed' : 'vanilla' }
  },
  methods: {
    stateChanged: function() {
      this.hasChanges = this.myModel.isChanged();
    },
    reset: function() {
      this.myModel.$rollback();
      this.hasChanges = this.myModel.isChanged();
    }
  }
});
</script>

For conveniance here's the template:

<div id="app">
  <h2>Model status: {{ status }}</h2>
  <div>
    <label for="name">
      Name:
      <input id="name" v-model="myModel.Name" @input="stateChanged" />
    </label>
  </div>
  <div>
    <p>Locked: {{myModel.locked}}</p>
    <form-toggle v-model="myModel.locked" @input="stateChanged"></form-toggle>
  </div>
  <div>
    <p>settings.dummy: {{myModel.settings.dummy}}</p>
    <form-toggle v-model="myModel.settings.dummy" @input="stateChanged"></form-toggle>
  </div>
  <button @click="reset">Reset</button>
  
  <h2>
    Raw output:
  </h2>
  {{ myModel }}
</div>

When I change the value of a non-nested property I'm unable to change the value of a nested property until I either reset ($rollback) the model or change the values back to their original state.

It feels like I'm missing something very obvious, but I've been trying to figure this one out for quite some time now. Hopefully you can shine some light on this?

How to set up a date field properly?

I've tried to setup a date field, but the v-model seems to give me trouble. With following code, I simply cannot type anything to the text input.

<template>
  <div>
    <input type="text" v-model="user.startDate"/>
    <pre>{{ userData }}</pre>
  </div>
</template>

<script>
  import {ReactiveModel} from 'vue-rawmodel';
  
  class User extends ReactiveModel{
    constructor(data = {}){
      super(data);
      this.defineField('startDate', {
        type: 'Date'
      });
      this.populate(data);
    }
  }
  
  export default {
    data(){
      return {
        user : new User({
          vm: this,
          dataKey: 'user'
        })
      }
    },
    computed:{
      userData(){
        return this.user.serialize();
      }
    },
    watch:{
      user:{
        handler: user => user.$validate(),
        deep: true,
        immediate: true
      }
    }
  }
  
</script>

example link: https://www.webpackbin.com/bins/-KmkBG8Nku2cQp0DVO_m

Any way to check if the field is dirty?

For example, create a new form with two field, username and password, both are required. To prevent immediate showing of error, the vue watch has set immediate:false. But when the user start typing
username, the password field would render error. It would be useful if there is something like user.getField('username').isDirty().

    <div>
      <input type="text" v-model="username" />
      <span v-if="user.getField('username').hasErrors()">
        {{ user.getField('username').errors | firstMessage }}
      </span>
    </div>
    <div>
      <input type="text" v-model="password" />
      <span v-if="user.getField('password').hasErrors()">
        {{ user.getField('password').errors | firstMessage }}
      </span>
    </div>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.