Note a debugging of Vue.js v-if
Today my workmate hit an issue that v-if didn't work for him.
It turned out that Vue.js can't watch the property that you do not define at the beginning.
It's not only relative to v-if. It impact all functions that used two-way data binding.
On below demo, we have two section that both of them hope to change content by button clicking. Section 1 works good but section 2 didn't.
It's because section2 object(in js) doesn't define content property.
So after Vue runs up, the new property that you add afterward can't be watched by Vue. And then you will fine your change will not reflect to web page even if you change the value of the property.
In this demo, I tried to change the content of section 2 but it didn't work. In my workmate's case, it change the value of a property but v-if was not triggered.
Live Demo: https://jsfiddle.net/Lawrence/7eq3y5uv/
When Vue.js starts, it will convert all data into observable. The key is how Vue.js do that here.
Vue.js will bind
Watcher on each properties of an object by defining
set method using Object.defineProperty. Therefore Vue.js can get updated if you change the value.
Apparently, if you don't define an property for an object at the beginning, Vue.js can't watch it.