1

Can I make 3 errors types without if/else?

I need to show 3 types of errors (they have different positions):

  • common
  • errorLogin
  • errorPassword

What I have now: I made a renderless function. And I see 2 ways:

  • use if/else in the template of the component:

    Component.vue

       <login-error-renderless
         v-if="isError"
         :errorMessage="errorMessage"
         :rowClass="$style.errorLogin"
         :colClass="$style.errorInner"
       >
       </login-error-renderless>
       <login-error-renderless
         v-else-if="isError && messageList[1]"
         :errorMessage="errorMessage"
         :rowClass="$style.errorPassword"
         :colClass="$style.errorInner"
       >
       </login-error-renderless>
       <login-error-renderless
         v-else-if="isError && !messageList[0] && !messageList[1]"
         :errorMessage="errorMessage"
         :rowClass="$style.errorWrap"
         :colClass="$style.errorInner"
       >
       </login-error-renderless>
    

RenderlessFunction.vue

 return h('div', { attrs: { class: this.rowClass } }, [
          h('div', { attrs: { class: this.colClass} }, [
            h('span', {}, this.errorMessage),
        ]),
  • use if/else in the renderless function (I'm using this now):

Component.vue

<login-error-renderless
    v-if="isError"
    :errorMessage="errorMessage"
    :classList="classList"
    :messageList = "messages"
>
</login-error-renderless>

Renderless.vue:

props: {
    errorMessage: String,
    classList: Object,
    messageList: Array,
  }, 

render(h) {
const createFunction = (rowClass, colClass = this.classList.innerClass) => h('div', { attrs: { class: rowClass } }, [
  h('div', { attrs: { class: colClass } }, [
    h('span', {}, this.errorMessage),
  ]),
]);

if (this.messageList[0] !== undefined) {
  return createFunction(this.classList.errorLogin);
}
if (this.messageList[1] !== undefined) {
  return createFunction(this.classList.errorPassword);
}
return createFunction(this.classList.error);

},

  • `v-if/v-else` seems pretty useful to me. Why do you want to avoid it? – wittgenstein Jul 18 '21 at 12:25
  • I hate many if/else (and this is the worst practice - to use many if/else where you can don't use it) and that is code repetition. point 2 (in this case) looks mutch better and this's the best what i could think of. But I want to know other ways if they exist – Алексей Jul 19 '21 at 01:12
  • I can only think of [dynamic components](https://vuejs.org/v2/guide/components.html#Dynamic-Components) with the example from the documentation. Every `if-case` is a `tab`. – wittgenstein Jul 19 '21 at 07:52
  • not is this case:) – Алексей Jul 19 '21 at 09:32

0 Answers0