Skip to content

Commit 9aa2c3a

Browse files
committed
feat(useVModel): new function useVModel
1 parent fe057e5 commit 9aa2c3a

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed

packages/core/useVModel/index.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# useVModel
2+
3+
> Shorthand for v-model binding, props + emit -> ref
4+
5+
## Usage
6+
7+
```js
8+
import { useVModel } from '@vueuse/core'
9+
10+
export default {
11+
setup(props, { emit }) {
12+
const data = useVModel(props, 'data', emit)
13+
14+
console.log(data.value) // props.data
15+
data.value = 'foo' // emit('update:data', 'foo')
16+
},
17+
}
18+
```
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { defineDemo } from '../../_docs'
2+
3+
defineDemo(
4+
{
5+
name: 'useVModel',
6+
category: 'Component',
7+
docs: require('./index.md'),
8+
module,
9+
},
10+
)

packages/core/useVModel/index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { computed, getCurrentInstance, isVue3 } from 'vue-demi'
2+
3+
export function useVModel<P extends object>(props: P, key: keyof P, emit?: (name: string, value: any) => void) {
4+
// @ts-expect-error mis-alignment with @vue/composition-api
5+
const _emit = emit || isVue3 ? getCurrentInstance()?.emit : getCurrentInstance()?.$emit
6+
7+
return computed({
8+
get() {
9+
return props[key]
10+
},
11+
set(value) {
12+
_emit(`update:${key}`, value)
13+
},
14+
})
15+
}

packages/z.placeholder.stories.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const sections = [
77
'Links',
88
'Showcases',
99
'State',
10+
'Component',
1011
'Sensors',
1112
'Browser',
1213
'Misc',

0 commit comments

Comments
 (0)