[Vuejs]-Is it possible to listen to in-DOM events with Laravel and VueJS?

0👍

Problems

There are a few reasons why this won’t work.

Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates.

As the error suggests, you can’t use uppercase letters for your event names as HTML attributes are case-insensitive.

One way to get around this issue is to use kabab-case i.e.

this.$emit('address-saved');
<address-form
    context="create"
    @address-saved="..."
></address-form>

The second issue would be that:

window.location.assign(route('customer.address.index'))

should be:

window.location.assign('{{ route('customer.address.index') }}') 

This is because the route function will be evaluated on the server and the returned value is what is sent to the browser so you’d need tell blade to echo the value and then you’d also need to wrap it in quotes.

Unfortunately, this won’t help either as you don’t have access to the window object inside the HTML event listener.


Solutions

There are a few alternatives you could try.

Firstly, you could simply pass the url to the component as a prop and then have the component handle the redirect.

HTML

<address-form
    context="create"
    redirect-on-save-url="{{ route('customer.address.index') }}"
></address-form>

Add the redirect-on-save-prop to the component:

props: ['redirect-on-save'],
//or
props: {
    'redirect-on-save': {
        type: String,
        required: true,
    }
},

Lastly, instead of your $emit you could have:

window.location.assign(this.redirectOnSaveUrl);


Alternatively, you could try adding your own $redirect method to Vue:

Vue.prototype.$redirect = function (url) {
    window.location.assign(url);
};

Then your HTML could be:

<address-form
    context="create"
    @address-saved="$redirect('{{ route('customer.address.index') }}')"
></address-form>

0👍

Have you try to put your event inside a v-on

<address-form
    context="create"
    v-on="{
        addressSaved: function(){ 
           window.location.assign(route('customer.address.index'))
        }
    }"
/>

Leave a comment