1. vue-coerce-props
Coerce props to custom values
vue-coerce-props
Package: vue-coerce-props
Created by: posva
Last modified: Mon, 23 May 2022 13:24:21 GMT
Version: 1.0.0
License: MIT
Downloads: 48,997
Repository: https://github.com/posva/vue-coerce-props

Install

npm install vue-coerce-props
yarn add vue-coerce-props

VueCoerceProps Build Status npm package coverage thanks Greenkeeper badge

Transform/Coerce props values to whatever you want

Installation

 npm install vue-coerce-props

Install the mixin globally or locally:

 // main.js
import CoercePropsMixin from 'vue-coerce-props'

Vue.mixin(CoercePropsMixin)
 // MyComponent.vue
import CoercePropsMixin from 'vue-coerce-props'

export default {
  // other options
  mixins: [CoercePropsMixin],
}

Usage

To coerce a prop, add a coerce function to any prop:

 const SpaceTrimmer = {
  props: {
    text: {
      type: String,
      // this function is called by VueCoerceProps
      coerce: text => text.trim(),
    },
    style: {
      type: String,
      coerce(style) {
        // you can access the context as in a computed property
        // NEVER use this.$coerced here as it would create an infinite loop
        // if you use things coming from data, you may consider using
        // a computed property instead
        return this.possibleValues.includes(style) ? style : 'default'
      },
    },
  },
}

VueCoerceProps will inject a computed property named $coerced containing every single coerced prop:

 <p>
  <span>Original value: {{ text }}</span>
  <span>Coerced value: {{ $coerced.text }}</span>
</p>

FAQ

  • Q: Why not passing component props as second argument?
    A: That would make every coerce value depend on every prop. At the end $coerced is just a computed property

License

MIT

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin