[Vuejs]-List of string after loop after returning

1👍

There were a couple of mistakes:

  1. method: should be methods:
  2. result.push cannot work if result is not an Array. You need to initialize it to [].
  3. When using {{text}} in the template, VueJS sanitizes the value so that it does not contain any HTML. But you’ll need HTML to force line returns. Hence, you need to use the v-html attribute instead (see code below).
  4. When you display an Array (result), it will automatically be converted to a comma-separated String. If that’s not what you want, you need to build the String yourself, which can be done with result.join('<br>').

Fixed demo (Also on Codepen):

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    multiLine: true,
    snackbar: false,
    text: 'I\'m a multi-line snackbar.'
  }),

  methods: {
    getResult(){
      const object = {brand: ['porsche'], model:['Cayman']};
      let result = [];
      for (let [key, value] of Object.entries(object)) {
        result.push(`${key}: ${value}`);
      }
      console.log(result);
      this.text = result.join('<br>');
      this.snackbar = true;
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script><style>.as-console-wrapper{display: none!important}</style>
 
<div id="app">
  <v-app id="inspire">
    <div class="text-center">
      <v-btn dark color="red darken-2" @click="getResult">
        Open Snackbar
      </v-btn>
      <v-snackbar v-model="snackbar" :multi-line="multiLine">
        <div v-html="text"></div>
        <v-btn color="red" @click="snackbar = false">
          Close
        </v-btn>
      </v-snackbar>
    </div>
  </v-app>
</div>
👤blex

Leave a comment