Vue3 Props v-if sync

Viewed 79

I'm making props with vue, but v-if doesn't work, and I'm wondering if the functions I've done are written correctly. I want the data from props to work synchronously. What are my mistakes made?

What functions does vue props check at startup?

<my-alert type="warning" appearance="outline" showIcon="false">Hello</my-alert>

myAlert.vue

<template>
<div class="block" :class="[typeClass,appearanceClass]">
    <div class="alert-icon" v-if="myIcon">
      <i>ICON</i>
    </div>
  </div>
</template>
<script>
const types =
    ['primary','accent','warn','basic','info','success','warning','error',
    ];
const appearances =
    ['border','accent','fill','outline','soft'];

import {defineComponent} from "vue";
import {computed} from "vue";

export default {
  props: {
    type: {
      type: String,
      default: 'primary',
      required: true,
      validator: value => {
        return ['primary', 'accent', 'warn', 'basic', 'info', 'success', 'warning', 'error'].includes(value)
      }
    },
    appearance: {
      type: String,
      default: 'border',
      required: true,
      validator: value => {
        return ['border', 'accent', 'fill', 'outline', 'soft'].includes(value)
      }
    },
    showIcon: {
      default: false
    }
  },
  computed: {
    typeClass() {
      return 'alert-type-' + this.type
    },
    appearanceClass() {
      return 'alert-appearance-' + this.appearance
    },
    myIcon() {
      return this.showIcon;
    }
  }
}
</script>
1 Answers

From your code what I can see, that you are passing the props shwoIcon like this showIcon="false", which is static passing and eventually pass false value as a string "false" not as Boolean value. So use props like this :shwoIcon="false" I mean use colon before showIcon which make the props dynamic. link

And Also in your my-alert component for showIcon props declear type for the better practice

showIcon: {
   type: Boolean,
   default: false,
},

Another way is, just simply change your computed property myIcon() to check the string props value, like this below,

myIcon() {
    return this.showIcon === "true";
}
Related