I'm working on a little project where I implemented a simple versioning system.
I have an array of objects (the diferent versions) that I wrap in a Proxy which will give me the informations of the desired version.
I use this object in a VueJs component and would like the view to be reactive when I change the version property of the Proxy.
How could I manage that ?
So far, to do so, I forgot about the proxy idea and just used a computed property. But I'd like to keep my Proxy for aesthetic reason.
Here is a simplified version of what I'd like
function versioning (versionArray) {
return new Proxy(versionArray, {
version: 0,
latest: versionArray.length - 1,
get: function (target, prop) {
if (["version", "latest"].includes(prop)) {
return this[prop];
} else {
return target[this.version][prop];
}
},
set: function (target, prop, val) {
if (prop === "version") {
return this.version = val;
} else {
return false;
}
}
})
}
let myData = versioning([
{
title: "My title",
description: "My first desption"
},
{
title: "THE title",
description: "My first description"
},
{
title: "THE title",
description: "It's a nice description"
}
]);
myData.version = myData.latest;
Vue.createApp({
data() {
return {
myData,
}
},
methods: {
version(val) {
this.myData.version = Math.min(Math.max(this.myData.version+val, 0), this.myData.latest);
}
}
}).mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.prod.min.js"></script>
<div id="app">
<button @click="version(1)">
<<
</button>
<div>{{myData.title}}</div>
<div>{{myData.description}}</div>
<button @click="version(-1)">
>>
</button>
</div>