How to convert the object to string in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To convert the object to string in VueJS. There are other methods to convert objects to strings, we are going to use JSON.stringify(Obj) methods. In these methods Obj stand for your object data.

Short solution

parentComp.vue

var Obj = {id:1,sitename:'sortoutcode',URL:'https://sortoutcode.com/'}; //object

var ObjA = JSON.stringify(Obj);

console.log(ObjA); // {'id':1,'sitename':'sortoutcode','url':'https://sortoutcode.com/'}

Today, I am going to show you How you convert the object to a string in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • Convert an object to a string using JSON.stringify()

This article will guide you to How do I convert the object to string in vueJS

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. The component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <FirstComp />
</template>

<script>
import FirstComp from "./components/FirstComp.vue";
export default {
  name: "App",
  components: {
    FirstComp: FirstComp,
  },
};
</script>

Convert an object to a string using JSON.stringify()

To convert the object to string in vuejs. We are going to define the object Obj in the data property. And we are going to convert this object into a string using the JSON.stringify(Obj).

Let’s take a short example to better understand.

FirstComp.vue

<template>
  <div class="app-data">
    <h1>Welcome to sortoutcode.com</h1>
    <div>
      <p>Obj: {{ Obj }}</p>
      <p v-if="output">Output: {{ output }}</p>
      <p v-if="output">Type: {{ typeof output }}</p>
      <button @click="showData">Convert</button>
    </div>
  </div>
</template>
<script>
export default {
  name: "FirstComp",
  data() {
    return {
      Obj: { id: 1, sitename: "sortoutcode", url: "https://sortoutcode.com/" },
      output: "",
      type: "",
    };
  },
  methods: {
    showData() {
      this.output = JSON.stringify(this.Obj);
    },
  },
};
</script>

For now, let’s check the output.

Output

convert object to string object

Links

Here, is the above program code sandbox link of how to convert the object to string in vue js. Then you can use it whenever you went and do the changes as per your requirements.

Codesandbox

All the best 👍.

Follow me on Twitter