简体   繁体   中英

Class as function in functional component - Vue

I am writing a simple functional component in vuejs. Currently stuck at a situation where I want to add conditional css class based on the props passed to it.

However the below doesn't work as expected and I am wondering what wrong am I doing here.

<script>
export default {
  name: "BasePill",

  functional: true,

  props: {
    variant: String
  },

  render(createElement, { children, props }) {

    const componentData = {
      staticClass: "text-sm text-center"
      class: function() {
        if (props.variant === 'secondary') {
           return 'bg-secondary'
        }

        return 'bg-primary'
      }
    };

    return createElement("span", componentData, children);
  },
};
</script>

The class property cannot be a function, it needs to be a string/array/object.

Do this instead:

const componentData = {
  staticClass: 'text-sm text-center',
  class: props.variant === 'secondary' ? 'bg-secondary' : 'bg-primary',
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM