Search code examples
nuxt.jsvuelidate

Using custom vuelidate function to access component methods in Nuxt


I have a method for getting the legal chess moves for any given square in a chess game, and I'd like to use it in a custom vuelidate function. These docs say that I should be able to access 'vm' by passing it in as a second argument but it's not working. I've tried this a bunch of different ways and only get various errors that seem related to not finding 'vm'. Rather than post the errors, I'll just relay what I'm trying to accomplish and post the current code here.

Here are my two validation functions defined outside of the export. I want them to both use the getLegalMoves() method from the component's methods. Putting 'vm' in the args is supposed to give access.

const legalActiveSquare = (square, vm) => { return vm.getLegalMoves(square).length() > 0 };
const legalTargetSquare = (values, vm) => { return vm.getLegalMoves(values.activeSquare).includes(values.targetSquare) };

Here are my validations:

validations: {
        activeSquare: { required, squareRegex, legalActiveSquare },
        targetSquare: { required, squareRegex, legalTargetSquare },
    },

Here is an example of one of the errors in computed:

computed: {
        activeSquareErrors () {
            const errors = [];
            if (!this.$v.activeSquare.$dirty) return errors
            !this.$v.activeSquare.required && errors.push('Required');
            !this.$v.activeSquare.squareRegex && errors.push('Should look like e4 or E4')
            !this.$v.activeSquare.legalActiveSquare(this.activeSquare, this.$vm) && errors.push('No legal moves for this square')
            return errors;
        }
}

So how can I scope into my component's methods from a vuelidate const?


Solution

  • I eventually came across this solution:

    The validation functions:

    var legalActiveSquare = (value, vm) => { return vm.getLegalMoves(vm.activeSquare).length > 0 };
    var legalTargetSquare = (value, vm) => { return vm.getLegalMoves(vm.activeSquare).includes(vm.targetSquare) };
    

    validations list:

    validations: {
            activeSquare: { required, squareRegex, legalActiveSquare },
            targetSquare: { required, squareRegex, legalTargetSquare },
        },
    

    example computed validation function:

    
            activeSquareErrors () {
                const errors = [];
                if (!this.$v.activeSquare.$dirty) return errors
                !this.$v.activeSquare.required && errors.push('Required');
                !this.$v.activeSquare.squareRegex && errors.push('Should look like e4 or E4')
                !this.$v.activeSquare.legalActiveSquare && errors.push('No legal moves for this square')
                return errors;
            },