Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this:

  watch: {
     search: function() {
        Crud.methods.getItems();
       }
    },

However, I encountered an error stating 'pagination is not defined' in my .vue file.

<template>
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-2">
                    <router-link :to="{ name: 'districts'}">
                               <span class="glyphicon glyphicon-chevron-left"></span>
                            </router-link>
                        {{ title }} {{pageTitle}}
                    </div>
                     <div class="col-md-4 search-wrapper">
                       <input type="text" v-model="search" 
                    placeholder="Search users.."/>
                    </div>
                    <div class="col-md-6 text-right">
                        <create-button :name="module+'-create'"></create-button>
                    </div>
                </div>
            </div>
            <div class="panel-body">
                <crud-index :columns="columns" :loading="loading" 
                   :pagination="pagination" @changePage="changePage">
                    <tr v-for="(item,index) in items" :key="item.id">
                        <td>{{ doMath(index) }}</td>
                        <td>
                            <router-link :to="{ name: 'users-edit', params: { id: item.id, disId:id }}">
                                {{ item.email }}
                            </router-link>
                        </td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.contact }}</td>
                        <td>{{ item.address }}</td>
                        <td>{{ item.age }}</td>
                        <td>{{ (item.gender==1)?'Male':''}} 
                        {{(item.gender==2)?'Female':''}}</td>
                        <td>{{ item.created_at }}</td>
                    </tr>
                </crud-index>
            </div>
        </div>
       </div>
       </div>
     </template>

     <script>
    import Crud from '../../components/Crud/Crud';
    import CrudIndex from '../../components/Crud/Index.vue';
    import CreateButton from "../../components/Crud/CreateButton.vue";

  export default {
    name: 'UsersIndex',
    mixins: [Crud],
    components: {
        CreateButton,
        CrudIndex
    },
    data() {
        return {
            columns: [
                {id: 0, name: 'ID', width: 5},
                {id: 1, name: 'E-mail', width: 20},
                {id: 2, name: 'Name', width: 20},
                {id: 3, name: 'Contact', width: 15},
                {id: 4, name: 'address', width: 20},
                {id: 5, name: 'age', width: 5},
                {id: 6, name: 'gender', width: 10},
                {id: 7, name: 'Created at', width: 20},
            ],
            search: '',
        };
    },
    watch: {
     search: function() {
        console.log(this.search);
        Crud.data();
        Crud.methods.getItems();
       }
    },
    methods:{
        doMath: function (index) {
         return (index+1) + ((this.pagination.currentPage-1)*5);
         }
    }
   };
   </script>

In my crud.js file, I need to set the "search" variable and call the getItems() method:

export default {
props: [],
data() {
    return {
        indexx: 0,
        loading: true,
        items: [],
        pageTitle: '',
        id: this.$route.params.id,
        search: this.$route.params.search,
        pagination: {
            isLoading: true
        },
    };
},
computed: {
    apiUrl() {
        return this.$store.getters.apiUrl;
    },
    module() {
        return this.$store.getters.module;
    },
    title() {
        return this.$store.getters.title;
    },
},
mounted() {
    this.getItems().then(() => {
        this.loading = false;
    });
},
methods: {
    getItems(page = 1) {
        return new Promise((resolve) => {
            this.setPaginationLoading();
            this.$http.get(this.getUrl(page)).then((response) => {
                this.items = response.data.data;
                this.setPagination(response.data);
                resolve();
            }, () => {
                this.$swal("Something went wrong. Try again!", '', "error");
            });
        });
    },
    getUrl(page = 1) {
        if (this.module == 'users') {
            let query = '&search=' + this.search;
            console.log('In nationality ', nation);
            return this.$store.getters.apiUrl + this.module + '?page=' + page + query;
        } else {
            return this.$store.getters.apiUrl + this.module + '/?page=' + page;
        }
    },
    setPaginationLoading() {
        this.pagination.isLoading = true;
    },
    setPagination(data) {
        this.pagination = {
            currentPage: data.meta.current_page,
            from: data.meta.from,
            lastPage: data.meta.last_page,
            to: data.meta.to,
            total: data.meta.total,
            isLoading: false
        };
    },
    changePage(page) {
        this.getItems(page);
    },
  },
};

}

Answer №1

When Crud is used as a mixin, all the properties become accessible through this on the Vue instance.

To invoke it, you would use:

watch: {
  search: function() {
    this.getItems();
  }
},

Answer №2

It appears that there may be a context issue here. Have you tried testing this code in your methods?

methods: {
    fetchItems(page = 1) {
      const self = this;
        return new Promise((resolve) => {
            self.showLoading();
            self.$http.get(this.generateUrl(page)).then((response) => {
                self.items = response.data.data;
                self.updatePagination(response.data);
                resolve();
            }, () => {
                self.showError("Something went wrong. Please try again!", '', "error");
            });
        });
    },
    generateUrl(page = 1) {
        if (this.module == 'users') {
            let query = '';
            if (this.search) {
              query = '&search=' + this.search;
              console.log('Search Query: ', query);
            }
          
            return this.$store.getters.apiUrl + this.module + '?page=' + page + query;
        } else {
            return this.$store.getters.apiUrl + this.module + '/?page=' + page;
        }
    },
    showLoading() {
      const self = this;
        self.pagination.isLoading = true;
    },
    updatePagination(data) {
      const self = this;
        self.pagination = {
            currentPage: data.meta.current_page,
            from: data.meta.from,
            lastPage: data.meta.last_page,
            to: data.meta.to,
            total: data.meta.total,
            isLoading: false
        };
    },
    goToPage(page) {
        this.fetchItems(page);
    },
  }
};

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

Converting CSS into jQuery

I am exploring ways to create a collapsible section with arrow icons (right and down arrows) in jQuery or JavaScript. Can anyone provide guidance on how to convert my CSS styling into jQuery code? Below is the jQuery approach I have attempted: $(document ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

Get the contents inside the window.open using Javascript

First and foremost, I want to acknowledge that I understand the likelihood of this failing due to cross-domain restrictions - just seeking confirmation on that. Here's my approach: I have a window that I open using JavaScript. Subsequently, I make an ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... https://i.sstatic.net/FFCRW.png My goal is to show the loading indicator when any action, like deleting an item or changing qua ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...

What is the method for specifying a null value in Typescript?

I'm curious if this code snippet is accurate, or if there's a better way to define it. Is there an alternative to using error!? I'm unsure of its meaning and would appreciate clarification. ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

Utilize Google Drive and scripts to incorporate map images into a React application

I'm currently working on setting up an album feature on my react website for a friend, and I would like the images in the album to be linked to a Google Drive so that he can easily upload new images whenever he wants. After successfully inserting the ...

Adjust the position of the object in relation to its current orientation

I am facing a challenge in moving an object upwards in relation to its current direction. I am working with a CubeGeometry that has a specific height, and my goal is to place an object at the top of it and have it rotate along with the cube. Simply adding ...

Transmit the canvas image and anticipate the AJAX POST response

I need to send canvas content to my API endpoint using ajax and wait for the response before moving on to the next function. Here is my current sending function: function sendPicture(){ var video = document.getElementById('video'); var canvas ...

How do I activate the <li> tag using jQuery?

I am currently implementing pagination on my webpage using the following JavaScript code: var pagingList = $('<ul>', {class: 'pagination list-unstyled list-inline'}); ...

What is the best way to calculate the combined total of radio button values using jQuery or JavaScript?

I recently came across a tutorial on how to sum radio button values using JavaScript or jQuery, and I decided to implement it in my code. However, I encountered some issues as it didn't work as expected. My goal was to offer users the option to downlo ...

I encountered a 404 Error message while attempting to access a specific express route

My Angular CLI generated app is running with an Express.js and MongoDB server. After running npm start, I can access http://localhost:3000, which routes to my homepage. The other links on the navbar work well to control routes, e.g., http://localhost:3000/ ...

List of COM ports accessible with Serialport npm

I am encountering an issue with a specific part of my program and although I have identified the problem, I am unable to find a solution on my own. Therefore, I am reaching out for your assistance. It seems like the problem does not lie within the serialp ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Exploring how to integrate a jQuery ajax request within Javascript's XmlHttpRequest technique

My current setup involves an ajax call structured like this: var data = {"name":"John Doe"} $.ajax({ dataType : "jsonp", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // re ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...