Currently, I am delving into creating a Vue.js application with Vue.js 3.0 to get acquainted with the Composition API. The simplicity of two-way data-binding in Vue.js 2.0 was one of its standout features for me. However, transitioning to the Composition API has left me uncertain about how to employ it, particularly when dealing with global state. For instance, within my app, there are two components illustrated in this Fiddle. Here's some code snippets:
HTML
<div id="my-vue" class="demo">
<banner :class="{ 'even-banner': isEven, 'odd-banner': !isEven }"></banner>
<hr />
<content :class="{ 'even-content': isEven, 'odd-content': !isEven }"></content>
<pre>value={{value}} isEven={{isEven}}</pre>
</div>
JavaScript
const store = {
state: Vue.reactive({
result: null
}),
generateNewValue() {
this.state.result = Math.floor(Math.random() * 10);
}
};
const MyApp = {
setup() {
const isEven = Vue.computed(() => store.state.result % 2 === 0)
const value = Vue.toRef(store.state, 'result')
return {
isEven,
value
}
}
}
const myApp = Vue.createApp(MyApp)
myApp.component("banner",
{
template: '<button @click="onGenerateClick">generate</button>',
setup(props) {
console.log('setting up...');
},
methods: {
onGenerateClick() {
store.generateNewValue();
}
}
}
);
myApp.component("content", {
template: '<div style="padding:2rem;">' +
'<div>Enter Value: <input type="text" v-model="result" /></div>' +
'<br /><div>or</div><br />' +
'<div><button @click="onGenerateClick">generate</button></div>' +
'</div>',
methods: {
onGenerateClick() {
store.generateNewValue();
}
}
});
myApp.mount('#my-vue')
CSS
.even-banner {
background-color:navy;
color: #fff;
}
.even-content {
background-color:blue;
color: #fff;
}
.odd-banner {
background-color:maroon;
color:#fff;
}
.odd-content {
background-color:red;
color:#fff;
}
The concept behind the design is straightforward - blue backgrounds for even numbers and red backgrounds for odd numbers. There is a "generate" button that functions correctly. Nevertheless, there is a text field where an input value can be manually entered, but unfortunately, it does not change the background color as intended. It appears as though two-way binding is faltering.
How can I implement two-way data binding effectively with a global state in a Vue.js application utilizing the Composition API?