Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS $watch $refs

Is it possible to $watch Vue $refs?

I'm wanting to set logic against a child component that is nested inside my current Vue instance but inside the ready callback, $refs.childcomponent is initially undefined while it's processed.

inside ready()

this.$watch('$refs', function() {     console.log("not firing"); }, { deep: true }); 

Result: Error: Maximum call stack exceeded

watch property of the instance

watch: {   '$refs': {      handler: function() { console.log("hit"); },      deep: true   } } 

result: nothing.

like image 733
Kiee Avatar asked Aug 19 '16 09:08

Kiee


People also ask

How do I watch $refs on Vue?

To watch refs with Vue. js, we can watch the reactive properties in the ref if the ref is assigned to a component. to watch the counter 's i reactive property. Since we assigned the counter ref to the counter component, i is a reactive property in counter .

What is REF () in Vue?

ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

How do I watch data changes on Vue instance?

Using watchers in Vue # vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.

Can you watch a computed property Vue?

You can put a watcher on any reactive property. This includes computed props, props, as well as data that is specified inside of data() on your Vue component. They're really useful for creating side effects — things that don't update your application's state immediately.


2 Answers

You can $watch $refs.<name>.<data> but not $refs.<name> itself, not to mention $refs.

https://jsfiddle.net/kenberkeley/9pn1uqam/

const Counter = {   data: () => ({     i: 0   }),   template: `<fieldset>     <p>Counter</p>     <code>i = {{ i }}</code>     <button @click="i += 1"> Add One </button>   </fieldset>` }  const App = {   components: { Counter },   mounted () {     this.$watch(         () => {             return this.$refs.counter.i         },       (val) => {         alert('App $watch $refs.counter.i: ' + val)       }     )   },   template: `<fieldset>     <p>App</p>     <counter ref="counter" />   </fieldset>` }  new Vue({     el: '#app',     render: h => h(App) }) 
like image 87
kenberkeley Avatar answered Sep 16 '22 13:09

kenberkeley


No, $refs are not reactive, watch won't work.

like image 22
Linus Borg Avatar answered Sep 20 '22 13:09

Linus Borg