Transform Vue array into Json

Asked

Viewed 509 times

2

I’m trying to pass on a textarea an array of Vue.js, and would like to turn it into json, what would be the best way to do that?

new Vue({
    el:"#app",    
    data : {
      nome_da_variavel_array: 
          '[{variavel : 'valor'},{variavel : 'valor'},{variavel : 'valor'}]'
    }
}); 
<textarea>{{nome_da_variavel_array}}</textarea>
  • Is there any code or example of what you want to do? .

  • I edited in question!

  • 2

    It would be easier to use the method JSON.stringify and take a real value and convert to JSON. I will formulate an example answer for you to see how it is.

1 answer

7

A good approach would be to create a computed Property that always returns an object from data converted to JSON.

var app = new Vue({
  el: '#app',
  data: {
    json: {
      teste: "Valor",
      um_array: [0, 1, 2, 99]
    }
  },
  computed: {
    json_string: function() {
      return JSON.stringify(this.json, null, '    ');
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
    <textarea style="width: 100%; height: 150px;">{{ json_string }}</textarea>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.