0
votes

I have an existing laravel blade template and am rewriting it using Vue components inside the blade template.
For example, one existing line in the blade template is:

<button class="btn-remove" onclick="removeItem('{{ $item->id }}', this);"></button>

This references a php function called removeItem.
Is there a way to call the php function in the new Vue component or do I have to redo the php function into javascript?

1
What is removeItem? I don't think this is a "php function" according to your code.Almaju

1 Answers

1
votes

I believe you mean that the template references a function removeItem that is defined somewhere in the JS scripts that run with your blade.

If you are migrating the whole blade into a VueJs Instance, you'll need to move the methods that are used by the Vue component into its ViewModel definition.

You would also need to pass any data coming from PHP as a prop or fetch it from an API So that the component can have access to it after its rendered.

For your example, the component would look something like this (using a prop).

Vue.component('MyComponent', {
    template:  `
        <div>
            <button class="btn-remove" @click="removeItem"></button>
        </div>
    `,
    props: {
        itemId: String
    },
    methods: {
        removeItem() {
            // Handle click event
            this.$emit('remove', this.itemId); // for example
        }
    }
})

And in your blade file, you would replace with:

<MyComponent item-id="{{$item->id}}"/>

Vue will replace the template above with the template specified in your component, and the PHP "bindings" will be passed as text into your HTML.