Vue Prop with Data fallabck
Vue mixin to support an optional prop that falls back to a local data
Installation
npm install vue-prop-data-fallback
Usage
The example below will create a prop named value
, a local variable _$value
(the fallback) and a computed property $value
.
<template> <input v-model="$value"></template> <script>import { propWithDataFallback } from 'vue-prop-data-fallback' // MySearch.vueexport default { mixins: [propWithDataFallback('value')], methods: { doSomething() { this.$value // the prop or the local value // it can be mutated normally // this will either change the local variable or emit an event this.$value = 'new value' }, },}</script>
Now the search input's value can be optionally controlled by the parent:
<!-- no control over the value -->
API
propWithDataFallback(prop: string, event?: string, propType?: Object, options?: { data: string, computed: string, initialValue: any }) => mixinObject
prop
: name of the prop that should be createdevent
: name of the event that should be emitted to enable the usage of.sync
orv-model
. Defaults to'update:' + prop
(to enable the.sync
modifier by default)propType
: value provided to the prop option. Can be a type likeString
,Boolean
, an array of types or an object (pretty much anything here). Defaults to{ required: false }
options
: extra options to customize the names of the data and computed propertiesdata
: name of the property added to data. Defaults to'_$' + prop
computed
: name of the property added to computed. Defaults to'_$' + prop
initialValue
: provides an initial value to be used when no prop is provided