vuejs reactivity without template
javascript, vue.js, vuejs2
Solution
You can `watch` props and use empty `render` function if you don't need to create any DOM elements:
new Vue({
el: '#app',
data: {
word: ''
},
components: {
'child' : {
props: ['myprop'],
watch: {
myprop: function(n, o) {
console.log('changed to: ', n)
}
},
render: function(h) {
return h() // avoid warning message
}
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<child :myprop="word"></child>
<button @click="word = 'one'">One</button>
<button @click="word = 'two'">Two</button>
<button @click="word = 'three'">Three</button>
</div>
Problem
I have a Vue component with an empty template that needs to listen to prop changes: ``` // component.vue <template> </template> <script> export default { props: ['mode'], updated: function() { console.log('updated!') } } </script> //parent.vue <template> ... <childcomponent :mode="variable"></childcomponent> </template> ... ``` Now whenever the parent's `variable` changes, I would expect `childcomponent.updated` to be called. However, this only seems to happen if the prop is used in the child's template. The only workaround I came up with so far is to set the child component's template to `<div v-show="false>{{ mode }}</div>`, but that really doesn't seem right? Is there a nicer way to solve my issue? The reason I'm using an empty template in the first place is because the component interacts with js library that does a bunch of DOM manipulations itself.