https://github.com/posva/vue-coerce-props
Coerce props to whatever you want
https://github.com/posva/vue-coerce-props
coerce props utility vue
Last synced: about 1 year ago
JSON representation
Coerce props to whatever you want
- Host: GitHub
- URL: https://github.com/posva/vue-coerce-props
- Owner: posva
- License: mit
- Created: 2018-04-18T14:58:13.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2021-09-27T22:21:12.000Z (over 4 years ago)
- Last Synced: 2025-04-21T01:49:34.436Z (about 1 year ago)
- Topics: coerce, props, utility, vue
- Language: JavaScript
- Size: 3.05 MB
- Stars: 72
- Watchers: 2
- Forks: 3
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- Contributing: .github/CONTRIBUTING.md
- Funding: .github/funding.yml
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# VueCoerceProps [](https://circleci.com/gh/posva/vue-coerce-props) [](https://www.npmjs.com/package/vue-coerce-props) [](https://codecov.io/github/posva/vue-coerce-props) [](https://github.com/posva/thanks)
> Transform/Coerce props values to whatever you want
## Installation
```sh
npm install vue-coerce-props
```
Install the mixin globally 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],
}
```
## Usage
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
Original value: {{ text }}
Coerced value: {{ $coerced.text }}
```
## 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](http://opensource.org/licenses/MIT)