search

Home  >  Q&A  >  body text

Unable to set attribute disable to button

<p>In the code shown below, I am developing a child component in which I have created a button and want to add the <code>disable</code> attribute. Given the following code, the <code>disable</code> attribute is underlined in red, and the error message reads: </p> <pre class="brush:php;toolbar:false;">Type '"isDigitizePolygonDisabled"' cannot be assigned to type 'Booleanish | undefined'</pre> <p>Please tell me how to correctly set the <code>disable</code> attribute <strong>code</strong>: </p> <pre class="brush:php;toolbar:false;"><template> <button id="idDigitizePolygonBtn" class="digitizePolygonBtn" disabled='isDigitizePolygonDisabled'> <slot></slot> </button> </template> <script lang="ts"> import { ref } from 'vue' let isDigitizePolygonDisabled = ref(true) export default { data() { return { isDigitizePolygonDisabled } }, props: { isDigitizePolygonDisabled: { type: Boolean, required: true }, } </script></pre> <p><br /></p>
P粉039633152P粉039633152494 days ago524

reply all(1)I'll reply

  • P粉376738875

    P粉3767388752023-08-17 12:21:54

    In Vue, when you want to bind a boolean property (such as disabled), you can use the v-bind directive (or its abbreviation :). This binds a property to an expression.

    If you try to bind the disabled property the way you do, Vue will think that you are trying to set the string "isDigitizePolygonDisabled" to the value of disabled, which is invalid. Hence the error you see.

    So, the final code will be:

    <template>
      <button id="idDigitizePolygonBtn" class="digitizePolygonBtn" :disabled="isButtonDisabled">
        <slot></slot>
      </button>
    </template>
    
    <script lang="ts">
    import { defineComponent, ref } from 'vue'
    
    export default defineComponent({
        props: {
            isDigitizePolygonDisabled: { 
                type: Boolean,
                required: true
            },
        },
        setup(props) {
            
            // For now, just return the prop
            return {
                isButtonDisabled: props.isDigitizePolygonDisabled
            }
        }
    })
    </script>

    I prefer using defineComponent and setup, I think it's more straightforward.

    Hope this helps!

    reply
    0
  • Cancelreply