Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Make $refs reactive so they can be used in computed properties and watchers

License

Notifications You must be signed in to change notification settings

posva/vue-reactive-refs

Repository files navigation

Make $refs reactive so they can be used in computed properties and watchers

Vue 2 only as you don't need this in Vue 3

Extremely Light < 0.2kb πŸ—œ

Installation

npm install vue-reactive-refs

Usage

This library exposes two different plugins: ReactiveRefs and DynamicReactiveRefs and you should only use one of them

ReactiveRefs

Supports all browsers but requires you to manually declare refs in component options.

import { ReactiveRefs } from 'vue-reactive-refs'
import Vue from 'vue'
Vue.use(ReactiveRefs)

MyComponent.vue

<template>
 <div>
 <input ref="input" />
 <button v-for="button in actions" ref="buttons">{{ action }}</button>
 </div>
</template>
<script>
export default {
 // this is necessary
 refs: ['input', 'buttons'],

 computed: {
 // NOTE: this is definitely not what you should use this lib for, but it's
 // the easiest example
 inputValue() {
 return this.$refs.input && this.$refs.input.value
 },
 // Same for this example. It's ALWAYS better to mapping your data (the source of truth)
 // and avoid at all cost mapping information to the DOM
 buttonsText() {
 return this.$refs.buttons && this.$refs.buttons.map(b => b.innerText)
 },
 },
}
</script>

DynamicReactiveRefs

Supports modern browsers (not IE) that support Proxy and works out of the box:

import { DynamicReactiveRefs } from 'vue-reactive-refs'
import Vue from 'vue'
Vue.use(DynamicReactiveRefs)

MyComponent.vue

<template>
 <div>
 <input ref="input" />
 <button v-for="button in actions" ref="buttons">{{ action }}</button>
 </div>
</template>
<script>
export default {
 computed: {
 // NOTE: this is definitely not what you should use this lib for, but it's
 // the easiest example
 inputValue() {
 return this.$refs.input && this.$refs.input.value
 },
 // Same for this example. It's ALWAYS better to mapping your data (the source of truth)
 // and avoid at all cost mapping information to the DOM
 buttonsText() {
 return this.$refs.buttons && this.$refs.buttons.map(b => b.innerText)
 },
 },
}
</script>

Related

License

MIT

About

Make $refs reactive so they can be used in computed properties and watchers

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Contributors 2

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /