vue-coerce-props
Version:
Coerce props to custom values
73 lines (55 loc) • 2.1 kB
Markdown
or locally:
```js
// main.js
import CoercePropsMixin from 'vue-coerce-props'
Vue.mixin(CoercePropsMixin)
```
```js
// MyComponent.vue
import CoercePropsMixin from 'vue-coerce-props'
export default {
// other options
mixins: [CoercePropsMixin],
}
```
To coerce a prop, add a `coerce` function to any prop:
```js
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:
```html
<p>
<span>Original value: {{ text }}</span>
<span>Coerced value: {{ $coerced.text }}</span>
</p>
```
* 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
[ ](http://opensource.org/licenses/MIT)
> Transform/Coerce props values to whatever you want
```sh
npm install vue-coerce-props
```
Install the mixin globally