Home > Blockchain >  Return vue component from a function
Return vue component from a function

Time:12-25

I'm new to Vue and I would want to render an SVG icon depending on task status and would like to create a re-usable function for that, How can I do that?

In React I could have done something like this:


const iconStatusMapping = {
  todo: <svg></svg>,
  processing: <svg>...</svg>,
  done: <svg>...</svg>
}

// utils.ts
export const getTaskStatusIcon = (status: TaskStatus) => {
  return iconStatusMapping[status]
}

function App() {
  const status = "todo"

  return (
    <div>{getTaskStatusIcon(status)} {status}</div>
  )
}


How can I do something similar in Vue3?

CodePudding user response:

In React, it may be not a good idea to define reused elements as JSX that is not wrapped in a function because element objects are expected to be new on every render. This may have no consequences for SVG icons but may have unexpected behaviour in other cases.

In Vue, this snippet could be directly translated to render function and JSX.

Static HTML like SVG icons can be safely defined as strings and outputted with Vue v-html, the same applies to React dangerouslySetInnerHTML:

const iconStatusMapping = {
  todo: `<svg></svg>`,
  ...
}

and

v-html="iconStatusMapping[status]"
  • Related