Home > Mobile >  What is the right way to call the query params in Vuejs?
What is the right way to call the query params in Vuejs?

Time:03-30

Updated code as per kissu code:-

comp.vue (starting point from here)

in mian.js routing given

    {
      path: "/DeploymentAttributeView/:id",
      name: "DeploymentRouteWithAttribute",
      component: DeploymentAttributeView,
    },
<tr v-for="(deployment, key) in deployments" :key="key">
  <td>
    <router-link :to="{
                  name: 'DeploymentRouteWithAttribute',
                  params: { id: deployment.DeploymentID },
                }">
      {{ deployment.Attribute }}
    </router-link>
  </td>

HelloWorld.vue

import axios from "axios";
export const deploymentattribute = ({ servicetype, id }) =>
  axios.get(
    `http://35.162.202.237:3000/servicedetail/?servicetype=${servicetype}&id=${id}`
  );
<template>
  <div>
    <div v-for="(attribute, index) in attributes" :key="index">
      {{ attribute.attribute }}
      {{ attribute.value }}
    </div>
  </div>
</template> 

<script>
import { deploymentattribute } from "./deploymentattribute";
export default {
  name: "DeploymentAttributeView",
  data() {
    return {
      attributes: [],
    };
  },
  async mounted() {
    const response = await deploymentattribute({
      servicetype: this.$route.query.servicetype,
      id: this.$route.query.id,
    });
    this.attributes = response.data;
  },
};
</script>

Issue with above code,

Unable to get the query string params dynamically. getting as undefined

Is there any way to pass them dynamically?

Codesandbox complete code:- https://codesandbox.io/s/combined-logic-api-forked-1973pk?file=/src/components/deploymentattribute.js

CodePudding user response:

Get the params id either by:

let urlParams = new URLSearchParams(window.location.search);
const id = urlParams.id;

or

 const id = this.$route.query.id;

Then instead of quotes use template literal to use variable value inside a string:

const id = this.$route.query.id;
axios.get(`http://35.162.202.237:3000/servicedetail/?servicetype={servicetype}&id=${id}`);

CodePudding user response:

You should have

import axios from "axios";
export const deploymentattribute = ({ servicetype, id }) =>
  axios.get(
    `http://35.162.202.237:3000/servicedetail/?servicetype=${servicetype}&id=${id}`
  );

and

<template>
  <div>
    <div v-for="(attribute, index) in attributes" :key="index">
      {{ attribute.attribute }}
      {{ attribute.value }}
    </div>
  </div>
</template> 

<script>
import { deploymentattribute } from './deploymentattribute'
export default {
  name: "DeploymentAttributeView",
  data() {
    return {
      attributes: [],
    };
  },
  async mounted() {
    const response = await deploymentattribute({ servicetype: this.$route.query.servicetype, id: this.$route.query.id })
    this.attributes = response.data
  },
};
</script>

Because you don't have the this context by default in a js file.

  • Related