Perform an action when a button is clicked in a VueJs single-page application

How can I trigger the refreshMailList function when clicking on the mail-list component?

This is my Vue instance with a custom mail-list component:

Vue.component('mail-list', {
  props: ['inboxmail'],
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button>Refresh</button>
  </div>
  `
  });


//Setting up the Vue object.
let options = {
  el: "#app",
  data: {
    pollingId: null,
    inbox: ''
  },

  created: function() {
    this.refreshMailList()
  },
methods:{
    refreshMailList: function(){
      fetch('/inbox')
      .then(response => response.json())
      .then(aJson => {
        this.inbox = aJson;
      })
    },

  } //end methods
} //end options

//Creating an instance of the ViewModel (vm)
let vm = new Vue(options);

In my index.html file, I have the following setup for the mail-list component:

      <div id="app">
        <mail-list v-bind:inboxmail="inbox" @refresh='refreshMailList'></mail-list>
      </div>

Answer №1

In order to trigger the event, it is necessary to emit it from within the mail-list component.

Give this code a try:

 Vue.component('mail-list', {
  props: ['inboxmail'],
  methods: {
    refresh: function() {
      this.$emit('refresh');
    },
  },
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button @click="refresh">Refresh</button>
  </div>
  `
  });

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 a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

The error message "Uncaught ReferenceError: e is not defined" is popping up in my code when

As a beginner with React and Material-UI, I am encountering an error that I cannot seem to resolve. When I load a component using material-ui/data-grid, the data grid simply displays "An error occurred" in the app. However, when I load the component withou ...

To prevent the animation from overflowing, set the parent element to have hidden overflow while still displaying the child element

I am facing an issue with two menus that can be toggled using a switch. Each menu item has a dropdown that appears when clicked. The problem arises when switching between the menus, as there is an animation for the transition (slide in and slide out). I wa ...

Vue.js and axios causing an empty array after the page is refreshed

As a newcomer to coding and using vue cli, along with my limited English skills, I apologize if I am unable to articulate the issue clearly. However, I am reaching out to the community for assistance. The code snippet below is from store.js where I fetch ...

What is causing the data not to react with the props in this particular scenario?

In addition to the central App.vue component, I have two other components - Rooms.vue and Desks.vue. When a swiper element in the Rooms.vue component is clicked, it triggers the opening of the Desks.vue component and emits the room object to App.vue. This ...

Exploring discrepancies in JSON arrays using Lodash

Using lodash to find the difference between two arrays: c1Arr contains: [ { varName: 'city', varValue: 'cccccccc' }, { varName: 'country', varValue: 'dddddddd' } ] c2Arr contains: [ { varName: 'abc', ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

What are the different kinds of properties that can be used in Vue.js

When working with Javascript, I can create arrays that hold different types of data elements like: var ex = ['name', 12, true]; console.log(ex); In Vue JS, when defining props for a component within a single file template, I have the option to ...

(React Native) Creating a visually appealing grid layout for displaying an array of item cards

I am working with two arrays named 'word' and 'definition' export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: ...

What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, whic ...

Is it possible to incorporate custom meta tags into next.js 13 using static metadata objects?

I'm trying to block Pinterest on my website by adding the meta tag <meta name="pinterest" content="nopin" /> in the site's header, but I'm uncertain how to do this in Next 13 using the new exported metadata object f ...

React - Updating child component each time the ref.current value is changed in the parent

Is it possible to make the child component Dashboard re-render whenever the value of showOfferDescription.current changes? I have found that using useRef is necessary in this case, as opposed to useState, because callback functions triggered by game.event ...

Retrieve information from an Express server using SweetAlert

Hi, I have created a web server using Node.js and Express. When I send a request to ip/test, it returns the text 'test' using res.send('test'). I am trying to fetch this text using sweetalert but I always encounter errors :( Here is t ...

Are elements loaded and hidden by ng-hide and ng-show, or does loading only occur with ng-show?

Is this method of programming effective for handling large elements such as 10 mb images? Are there alternative solutions that would work better? ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

Changing a value within a JSON object

I need to update the "Last" Price for MarketName USDT-BTC. How can I change the value from 16750.00000001 to 17000.00000001 and then transmit it through my API? { "success":true, "message":"", "result":[{ "MarketName":"USDT-BTC", "High":16 ...

AngularJS continues to display an "Invalid Request" message whenever the requested resource is unavailable

When I try to fetch a group of images through AJAX and exhibit them on the page using ng-repeat, an issue arises with the image source tags. These tags send incorrect requests to the server before the collection is retrieved, leading to error messages in t ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...