Exporting VueJS-rendered HTML with checkbox fails to preserve checked state

Viewed 233

My component template contains the following checkbox code:

<div ref="htmlData">
    <input 
        type="checkbox" 
        class="mycb" 
        :id="uniqID" 
        :disabled="disabled"
        v-model="cbvalue"
    >
</div>

(parts removed for simplicity).

I need to create a PDF out of this template (on server). This is what i'm doing in the code:

methods : {
    save () {
        let saveData = {
              'html': this.$refs.htmlData.innerHTML 
            };
        this.$http.post('/api/save',saveData);
    }
}

However, the saved HTML doesn't contain checkbox state, so it always saves an unchecked checkbox.

Here's a slightly modified jsfiddle.

My question is: how can I capture the checkbox state in the rendered HTML?

I tried adding :checked="cbvalue" prop - no luck

1 Answers

It looks like there's no way to bind the checked attribute of an input; Vue does everything through the property. (For reference, the property is the internal state, the attribute is what shows up in the HTML.)

To get the attribute to reflect the property, you can add a little directive.

var demo = new Vue({
  el: '#demo',
  data: () => ({
    val: false
  }),
  methods: {
    save() {
      console.log(this.$refs.main.innerHTML);
    }
  },
  directives: {
    explicitChecked: {
      update(el) {
        if (el.checked) {
          el.setAttribute('checked', 'checked');
        } else {
          el.removeAttribute('checked');
        }
      }
    }
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="demo">
  <button @click="save">save</button>
  <div ref="main">
    <input type="checkbox" v-model="val" v-explicit-checked>
  </div>
</div>

Related