Search code examples
javascripthtmlarraysvue.jsdropdown

How to show HTML from this array Vue JS


I'm new to Vue JS and I'm trying to pass an HTML table using this array, I have a dropdown where I select the option I want and then it shows it, but I can't figure out how can I put HTML in there, when I do it prints code instead. A little help would be greatly appreciated.

This is the HTML file:

        <div id="app">
            <div>
              {{pickedValue}}
            </div>
            <picker v-model="pickedValue"></picker>
        </div>

This is the JS file and I want to put an HTML table inside list:["c","d","e"]

  console.clear()

Vue.component("picker",{
  props:["value"],
  data(){
    return {
      list:["c","d","e"],
      currentValue: this.value,
      selectedValue: ""
    }
  },
  template:`
    <div>
      <select @change="currentValue = $event.target.value" v-model="selectedValue">
          <option value="">Select</option>
          <option v-for="item in list" :value="item" :key="item">{{item}}</option>
      </select>
    </div>
  `,
  watch:{
    currentValue(newValue){
      if (!this.list.includes(newValue))
        this.selectedValue = "" 

      this.$emit('input', newValue)
    }
  }
})

new Vue({
  el:"#app",
  data:{
    pickedValue: null
  }
})

Solution

  • You should use v-html instead. Be careful when using this because if "c", "d", "e" are user inputs, it could expose your application to XSS attacks:

        <div id="app">
            <div v-html="pickedValue"></div>
            <picker v-model="pickedValue"></picker>
        </div>
    

    https://v2.vuejs.org/v2/api/#v-html