outside vue component access method is not recommended

I am a newcomer to Vue.js and have implemented a comment feature similar to the one described here. However, due to certain constraints, I had to make adjustments. I used a Vue component but encountered an issue where it couldn't access a method inside my Vue instance. The requirement is that any user can reply to a particular comment if another user has already posted a comment. I am receiving a Vue warning stating "Property or method 'replyComment' is not defined on the instance but referenced during render". Can anyone offer assistance with this problem, please?

Vue.component('reply-komen',{
        template:'#replykomen',
        props:{
            edit:{
                type:Boolean,
                default:false
            },
            comment:{
                type:Object,
                default(){
                    return {
                        title: '',
                        body: '',
                        id: ''
                    }
                }
            }
        },
        methods:{
            replyComment: function(comment_id){
                console.log(comment.id);
                var id={{$complaint->id}};
                var users={{Illuminate\Support\Facades\Auth::user()->id}};
                const item=this.$refs.balaskomen;
                const idkomen=item.dataset.id;
                console.log(idkomen);
                $.ajax({
                    url:'/api/complaint/comment',
                    type:"POST",
                    data:{
                        'users':users,
                        'id':id,
                        'comment':this.comment
                    },
                    success:function (response) {
                        komen2.comment.body= '';
                        komen2.fetchComments();
                    }
                })
            }
        }
    });

    var komen2=new Vue({
        el: '#kalas',
        data:{
            currentView:'',
            edit:false,
            comments:[],
            comment: {
                title:'',
                body: '',
                id: '',
            }
        },

        created: function(){
            this.fetchComments();
            this.createComment();
            this.editComment();
            this.deleteComment();
            this.showComment();
        },

        methods: {
            fetchComments: function(){
                var id={{$complaint->id}};
                $.ajax({
                    url:'/api/complaint/getcomments',
                    type:"GET",
                    data:{
                      'id':id
                    },
                    success:function (response) {
                        komen2.comments = response;
                    }
                })
            },

            createComment: function(){
                var id={{$complaint->id}};
                var users={{Illuminate\Support\Facades\Auth::user()->id}};
                $.ajax({
                    url:'/api/complaint/comment',
                    type:"POST",
                    data:{
                        'users':users,
                        'id':id,
                      'comment':this.comment
                    },
                    success:function (response) {
                        komen2.comment.body= '';
                        komen2.fetchComments();
                    }
                })
            },

            editComment: function(comment_id){
                $.ajax({
                    url:'/api/complaint/'+window.Laravel.post_id+'/comment'+comment_id,
                    type:"PATCH",
                    data:{
                        'comment':this.comment
                    },
                    success:function (response) {
                        komen2.comment.body= '';
                        komen2.comment.id= '';
                        komen2.fetchComments();
                        komen2.edit = false;
                    }
                })
            },

            deleteComment: function(comment_id){
                $.ajax({
                    url:'/api/complaint/'+window.Laravel.post_id+'/comment'+comment_id,
                    type:"DELETE",
                    success:function (response) {
                        komen2.comment.body= '';
                        komen2.fetchComments();
                    }
                })
            },

            showComment: function(comment_id){
                for (var i = 0; i < this.comments.length; i++) {
                    if (this.comments[i].id == comment_id) {
                        this.comment.body = this.comments[i].body;
                        this.comment.id = this.comments[i].id;
                        this.edit = true;
                    }
                }
            }
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="kalas">
    <div class="container">
        <h4>Add Comment</h4>
        <form action="" @submit.prevent="edit ? editComment(comment.id) : createComment()">
            <div class="input-group">
                <textarea name="body" v-model="comment.body" ref="textarea"  class="form-control"></textarea>
            </div>
            <div class="input-group">
                <button type="submit" class="btn btn-primary" v-show="!edit">Add Comment</button>
                <button type="submit" class="btn btn-primary" v-show="edit">Edit Comment</button>
            </div>
        </form>
        <br>
        <h4>Comments</h4>
        <ul class="list-group" v-for="comment in comments">
            {{--<li class="list-group-item" v-for="comment in comments">--}}
                <form>
                    <div class="input-group">
                        <textarea class="form-control">@{{comment.body}}</textarea>
                    </div>
                    <div class="input-group" ref="balaskomen" v-bind:id="comment.id">
                        <a class="btn btn-default" v-on:click="currentView='reply-komen'">Reply</a>
                        <a class="btn btn-danger" v-on:click=" deleteComment(comment.id)">Delete</a>
                    </div>
                </form>
            {{--</li>--}}
        </ul>
        <div class="container balas" >
            <component :is="currentView"></component>
        </div>
    </div>
</div>
<template id="replykomen" >
    <form action="" @submit.prevent="replyComment(comment.id)">
        <div class="input-group">
            <textarea name="body" v-model="comment.body" ref="textarea"  class="form-control"></textarea>
        </div>
        <div class="input-group">
            <button type="submit" class="btn btn-primary" v-show="!edit">Add Comment</button>
        </div>
    </form>
</template>

Answer №1

The function replyComment is currently located in the second Vue instance with the ID #kalas, however, it is being used in the template of the first Vue instance with the ID #replykomen. To fix this issue, you should move or duplicate the function to the methods section of the first Vue instance.

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

Unveil Information with Underscore JS

I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Is it possible for the r.js optimizer to generate a fresh index.html file that links to the compiled files

After using r.js to optimize my project, I'm wondering how to generate a single index.html file that includes just one optimized script and one CSS file. Would I need to manually write this post-build or is there another way to achieve this? ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

Convert an object to a custom array using JavaScript

I need to transform the following object: "age": [ { "Under 20": "14", "Above 40": "1" } ] into this structure: $scope data = {rows:[ {c: [ {v: "Under 20"}, {v: 14} ]}, {c: [ {v: "Above 40"}, ...

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

Guide on establishing two loops in React JS

I'm receiving a JSON array that contains nested arrays. I attempted to iterate through it using two loops, but so far, I haven't been successful. {this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) => {alarms.repo ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

What is preventing the addition of links to the navigation bar when using a sticky navigation bar?

Currently, I am in the process of developing a blog website using Django. One of the features I have successfully implemented is a sticky navigation bar. However, I am facing a challenge with adding links to the menu on the navigation bar due to existing ...

Any idea how to dynamically insert rows and columns into a table or div element?

Can anyone assist me with this task? I have successfully completed the visual process I intended to do. How can I achieve this structure using AngularJS? The data will be stored in Json format. When the "+" symbol is clicked in a certain direction, the fi ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

Transferring data from one HTML element to another using Angular [Ionic]

My project involves utilizing an ionic slide box to display a series of images within it. <ion-slide-box> <!-- I am looping through the images based on the image count --> <ion-slide ng-repeat="n in [].constructor(imageCount) track by $in ...

Assemblage of Marionettes: Adding multiple elements to the DOM

I am working on a Marionette application and have come across an issue with inserting new tab items. I have a collection of tabs, but when adding a new item, I need to insert DOM elements in two different areas. The problem is that Marionette.CollectionV ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

Changing the 'badge' to 'panel' within the UI framework of 'ant design' has been set

Can the Badge be placed next to 'Info' in a Panel using ant design? https://i.sstatic.net/Lldc7.png View Code <div> <Collapse> <Panel header="Info" key="1"> <Badge count={4} style={{ b ...

Error occurred while making a request to https://registry.npmjs.org/corepack. Failed due to connection issue: unable to reach the host

Previously, NPM was functioning without any issues, but now I am facing a problem where any attempt to connect to the registry results in a timeout. When using NPM, I receive an error message stating request to https://registry.npmjs.org/corepack failed, ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...