Exploring this simple example, we have an input
and a p
element that displays the input value:
const App = {
data() {
return {
message: "hello world!"
};
}
};
Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
<input v-model="message"/>
{{ message }}
</div>
Initially, changing the input text updates the content of the p
element. However, if we replace data()
with setup()
, the changes to input
no longer reflect in the p
:
const App = {
setup() {
return {
message: "hello world!"
};
}
};
Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
<input v-model="message"/>
{{ message }}
</div>
To address this issue, we can use ref
for the message
:
const App = {
setup() {
const message = Vue.ref("hello world!");
return {
message
};
}
};
Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
<input v-model="message"/>
{{ message }}
</div>
But why is this necessary? Why doesn't it work as expected by default?
One possible explanation is that the object returned from data()
is internally made reactive, while the object returned from setup()
may not be observed because it could include methods that do not require monitoring. However, when examining
inputEl.__vueParentComponent.setupState
, it appears to be a Proxy
. So, why doesn't it behave as anticipated?