Search code examples
javascriptnode.jsvue.jsvuexquasar

pass variables from front to backend


i have a vue js project with front end and i have a field with variables that i want it when its changed it will go to backend and change there too any idea? the variable is id tage like in this code

app.get('/payments', (request, response) => {
  response.set('Access-Control-Allow-Origin','*')
  let payments = []


db.collection("payments").where("id", "==", idtag).get().then(snapshot => {
  snapshot.forEach((doc) => {
    console.log(doc.id, '=>', doc.data())
    payments.push(doc.data())
  })
  response.send(payments)
  console.log('payments:',payments)
})
})

and this is the front end

export default defineComponent({

  setup () {
    const loadinga = ref(false)
    const idtag=ref(null)
    const filter = ref('')
return {
      events: [ '2019/02/01', '2019/02/05', '2019/02/06' ],
      date : ref('2019-02-22 21:02'),
      columns,
      loadinga,
      idtag,

Solution

  • Make the ID part of the request url:

    // backend assuming this is express
    app.get('/payments/:id', (request, response) => {
        // use the id in some way
        const idtag = req.params.id;
        ...
    });
    

    In your frontend code, you need to watch the idTag and initiate a new request each time it changes.

    // frontend
    import { defineComponent, ref, watch } from "vue";
    
    export default defineComponent({
      setup() {
        const idtag = ref(null);
    
        watch(idtag, (newValue, oldValue) => {
          fetch(`/payments/${newValue}`)
            .then(raw => raw.json())
            .then(data => {
              // do something with the data
              console.log(data)
            })
            .catch(console.warn);
        });
    
        return { idtag };
      }
    })
    

    If you need this to run immediately, you should use watchEffect instead. But since your value is null at the beginning, I don't think this is the case.