Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to import axios.post in watch in vue?

I want to import axios.post in the watch?

methods: {
    sendData() {
        console.log('Sending data:', this.date, this.product_id, this.warranty_id);
        axios.post('{{ route('product.warranty.save') }}', {
            date: this.date,
            product_id: this.product_id,
            warranty_id: this.warranty_id,
        })
            .then(response => {
                this.dates.push(response.data.date);
                this.products.push(response.data.product_id);
                this.warranties.push(response.data.warranty_id);
            })
            .catch(error => {
                console.log('Error:', error);
            });
    }
},
watch: {
    date(newDate) {
        const showType = document.getElementById('showType');
        showType.textContent = newDate;
    }
},
0 likes
1 reply
LaryAI's avatar
Level 58

To import axios.post in the watch in Vue, you can simply import axios at the top of your component and then use it in the watch like this:

import axios from 'axios';

export default {
  data() {
    return {
      date: '',
      product_id: '',
      warranty_id: '',
      dates: [],
      products: [],
      warranties: [],
    };
  },
  methods: {
    sendData() {
      console.log('Sending data:', this.date, this.product_id, this.warranty_id);
      axios.post('{{ route('product.warranty.save') }}', {
        date: this.date,
        product_id: this.product_id,
        warranty_id: this.warranty_id,
      })
        .then(response => {
          this.dates.push(response.data.date);
          this.products.push(response.data.product_id);
          this.warranties.push(response.data.warranty_id);
        })
        .catch(error => {
          console.log('Error:', error);
        });
    },
  },
  watch: {
    date(newDate) {
      const showType = document.getElementById('showType');
      showType.textContent = newDate;
      axios.post('{{ route('product.warranty.save') }}', {
        date: newDate,
        product_id: this.product_id,
        warranty_id: this.warranty_id,
      })
        .then(response => {
          this.dates.push(response.data.date);
          this.products.push(response.data.product_id);
          this.warranties.push(response.data.warranty_id);
        })
        .catch(error => {
          console.log('Error:', error);
        });
    },
  },
};

In this example, we imported axios at the top of the component and then used it in the watch for the date property. Whenever the date property changes, we make a POST request to the server using axios.post and update the dates, products, and warranties arrays with the response data.

Please or to participate in this conversation.