首页 > 解决方案 > Does a reusable component in vuejs require an id compulsorily?

问题描述

I have a toggler component in vuejs.(CheckBox.vue) The tempate is as follows and the toggler works as long as I provide the input field an id. But I cant use id because there are multiple togglers in another component. When i remove id of checkbox, it doesnot work. What is the reason this is happening and how to fix this?

<template>
<div class="checkbox">
    <label for="checkbox" class="switch">
      <input type="checkbox" id="checkbox" v-model="checked" @click="onChange">
      <span class="slider round"></span>
    </label>
  </div>
</template>
<script>
export default {
  name: 'CheckBox',
  props:{
    defaultChecked:{
      type:Boolean,default:true
    }
  },
  data:function(){
    return {
      checked: this.defaultChecked
    }
  },
  methods:{
    onChange:function(){
      this.checked=!this.checked;
      this.$emit('status',this.checked)
    }
  }
}
</script>

This code works fine if I give id to checkbox and include it in another component. But when I remove id, the toggler stops to work.The component is:

//component
<div>
<CheckBox  v-model="this.checkbox" @status="changeStatus" style="float:right"></CheckBox>

//Script

import CheckBox from './CheckBox.vue'
export default {
    name: 'Brands',
    components:{
      CheckBox
    },
    data:function(){
      return {
        checkbox:true
      }
    },
    methods:{
      changeStatus:function(){
        this.checkbox = !this.checkbox
      }
    }
}

标签: javascriptvue.js

解决方案


推荐阅读