[Vuejs]-How to select first radio button without knowing the value using vue.js (and v-model)

0👍

You can set the initial value of r in the mounted hook of the component to the value of the first radio button:

mounted() {
  this.r = this.$el.querySelector('input[type="radio"]').value;
}

But it might be better to use a fixed template for the component that isn’t rendered by the server in the first place. Instead of rendering HTML, you could render JavaScript containing the data for the items you want and then bind that data to the template.

Vue works best when the template is generated from the data instead of the other way around.

<script>
  // Rendered by the server external to the Vue component,
  // otherwise just render directly into the component's data
  window.items = [
    { label: 'Apple', value: 'apple' },
    { label: 'Orange', value: 'orange' },
  ];
</script>
<label>
  <input v-model="selected" v-for="item of items" type="radio" :value="item.value">
  {{ item.label }}
</label>
new Vue({
  el: "#app",
  data: {
    items: window.items,
    selected: window.items[0].value,
  },
});

Leave a comment