Skip to content
Advertisement

Vue.js not setting data

I’m trying to do some simple form validation using Laravel 5.3 and Vue.js.

Laravel controller:

 public function test(IlluminateHttpRequest $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'date' => 'required'
        ]);
...
    }

Vue data:

let app = new Vue({
        el: '#app',

data: {
        submitted: false,
        errors: [],
        post: {
               name: '',
               date: '',
              },
},

Vue post:

Vue.http.post('url', post).then((response) => {
    // form submission successful, reset post data and set submitted to true
    app.post = {
        name: '',
        date: '',
    };

    // clear previous form errors
    app.$set('errors', '');

    app.submitted = true;

}, (response) => {
    // form submission failed, pass form  errors to errors array
    console.log(response.data.name); //"The Name field is required."
    app.$set('errors', response.data); // TypeError
});

I’m getting

TypeError: can’t assign to properties of (new String(“errors”)): not an object

with app.$set('errors', response.data);

Where am I going wrong?

Advertisement

Answer

Check vm.$set(object, key, value), you’re trying to add a property to the string ‘errors’ using response.data as the key.

The correct syntax is app.$set(app, 'errors', response.data) but app.errors = response.data should work equally well.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement