Using Laravel with VueJS: Executing VueJS Function from Blade Template

I've been searching for solutions and references to resolve my issues. I'm struggling with calling a Vue method (e.g., createItem() {...}) that is located inside a VueJs component using an external button.

Here is my "app.js" file:

// ..\resources\assets\js\app.js
require('./bootstrap');

window.Vue = require('vue');
window.Vue.prototype.$http = axios;

Vue.component('sample', require('./components/SampleComponent.vue'));

const app = new Vue({
    el: '#app',
    methods: {
        createItem: function() {
            // What should go here?
        }
    }
});

SampleComponent.vue file:

<template>
...
</template>

<script>
    export default {
        mounted() {
            this.getItems();
        },
        data() {
            return {
                items: [],
                newItem: {'name': '', 'description': ''},
                fillItem: {'id': '', 'name': '', 'description': ''}
            }
        },
        methods: {
            getItems() {
                axios.get( 'api/data' ).then( response => {
                    let result = response.data;
                    this.items = result;
                })
            },
            clearItem(){
                this.newItem = {'name': '', 'description': ''};
                this.fillItem = {'id': '', 'name': '', 'description': ''};
            },
            createItem(){
                var self = this;
                $("#create-role").on("hidden.bs.modal", function () {
                    self.clearItem();
                }).modal('show');
            },
        }
    }
</script>

index.blade.php file:

<div id="app">
...

<!-- Load samplecomponent in blade template -->
<sample></sample>

<!-- How can I trigger the method inside SampleComponent.vue using an external button? -->
<button type="button" class="btn btn-sm" @click="createItem" id="external-button">Create new item</a>

</div> <!-- End of App -->

I've gone through the documentation, but I still haven't succeeded. Apologies for the basic question, as I am new to VueJS. Thank you for all your assistance.

Answer №1

Your code needs fixing because you closed the <button> with </a> instead of </button>

<button ... @click="createItem" id="external-button">Create...</a>

In addition, createItem is a function, so remember to include parentheses!

Updated code:

<button type="button" class="btn btn-sm" @click="createItem()" id="external-button">Create new item</button>

Answer №2

If you want to access a child's method, you can use a ref:

Example:

<div id="app">
  <sample ref="child"></sample>
  <button type="button" class="btn btn-sm" @click="callChildMethod" id="external-button">Call child method</a>
</div>

Parent component:

const app = new Vue({
    el: '#app',
    methods: {
        callChildMethod: function() {
            this.$refs.child.methodName()
        }
    }
});

Alternatively, you could use events to communicate between components (there are plugins available to simplify event handling):

Parent component:

const app = new Vue({
    el: '#app',
    methods: {
        callChildMethod: function() {
            this.$events.fire('childMethodName')
        }
    }
});

Child component:

export default {
        ...
        methods: {
           ...
            methodName(){
                // do something
            },
        },
        events: {
          childMethodName () {
            this.methodName()
          }
        },
    }

Source:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize error messages in Vue Formulate inputs

Currently, I am using Vue Formulate for form validation. After submitting the form, an error message displays as Formid is required.. However, I would prefer it to display Form ID is required <FormulateForm class="login-form" v-mod ...

JavaScript function is not being invoked when receiving PHP arguments

When using the < a > tag in php, I encountered an issue where passing an argument in a JavaScript function did not result in the function being called. However, if I passed empty arguments, the function was executed. Here is the JavaScript code: fu ...

Encountering CORS Problem when Logging in to LastFM API

I have been experimenting with the lastFM API. To begin, I created a simple template focused on connecting to the LastFM API and authenticating myself. In my HTML page, there is a button- <button id="auth">AUTHENTICATE</button> Below is the j ...

How can the get method in PHP be employed to perform various functions?

I created a PHP script called user.php to redirect users to different websites based on the name parameter in the URL. Here is the PHP code: <?php $id = $_GET["name"] ; if ($id == "joe") { header('Location: http://1.com'); } if ($id = ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

What is the best way to integrate vanilla JavaScript code into my React JS application?

I've been experimenting with allowing users to download songs to an audio playlist using input and FileReader() in regular JavaScript, but I'm encountering a display issue. Most of my code is written in vanilla JavaScript, and I'm hesitant a ...

Mongoose .lean() Method Causes Equality Test to Fail

In my quest to compare req.user._id with an array of ObjectIds obtained from a MongoDB query, I encountered failures in all my attempts using .includes(), as well as strict and loose equality checks. Below is a simplified version of the logic in my contro ...

Dynamically transferring data from PHP to JavaScript in dynamically generated HTML elements

I have a collection of entities retrieved from a database, each entity containing its own unique GUID. I am showcasing them on a webpage (HTML) by cycling through the entities array and placing each one within a new dynamically generated div element. < ...

A strategy for concealing the selected button within a class of buttons with Vanilla JS HTML and CSS

I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multip ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Node.js 0.12 now offers access to the latest ECMAScript 6 features

The latest version of Node.js (0.12) has been released with an updated Google's v8 JavaScript engine, v3.28.73. Which ECMAScript 6 features are currently available in Node.js without using the --harmony flag? I have searched multiple websites that c ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

Comparing AngularJS Style Guides: Insights from Todd Motto, John Papa, and Minko Gechev

As someone new to Angular, I am eager to establish good practices right from the start. I have discovered three compelling Angular style guides, each with its own strengths. However, since I lack experience with large Angular applications, I find myself un ...

The command 'npm run dev' is not displaying the Event line in the command prompt, and the localhost is getting stuck on the loading screen

Any recommendations would be greatly welcomed! (and just to clarify, I'm fairly new to all of this). I've gone through the process of clearing cache, disabling the firewall, restarting my computer, reinstalling Nodejs, and even starting the proj ...

Establishing communication between a parent window and a popup window that have distinct domains

I'm currently developing a browser extension using JavaScript. My main tasks include: Sending javascript objects from a webpage located at "foo.com" to a popup page on "bar.com" For example, from "foo.com/some_page/" to "bar.com/another_page.htm ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Is there a method in CSS animations that allows for endlessly repeating successive animations in a specified sequence?

While working with CSS animations, I encountered a challenge of making two animations occur successively and repeat infinitely without merging keyframes. Is there a way to achieve this using only CSS? If not, how can I accomplish it using JavaScript? I a ...

Bootstrap's Well Size Has Been Set into Place

Is there a way to keep the size of a text display container fixed while still making it responsive when cycling through different lengths of text with a button click? <div class ="col-md-6"> <p id="quote">Delighted with m ...

Is it necessary to configure Webpack or use a plugin to remove console.log() statements by default in an Angular Application, or does it do so automatically?

Welcome to my first post! I hope I can effectively communicate the question and the background that led me to ask it. I am relatively new to web programming, with about 1 and a half years of experience working with Java, JavaScript, and TypeScript using An ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...