Actualmente estoy trabajando en una aplicación con three.js
y vue.js
Cuando hago clic en el modelo 3D, se activa una función en la que el nombre de la parte del modelo en la que se hizo clic se establece en la variable "nombre" , que luego debe representar vue.js.
Al pageload
la página, se representa el valor inital
de "nombre" en este ejemplo HELLO . Pero cuando hago clic en el modelo, la variable "nombre" se actualiza pero no la variable de datos "propiedad" en vue.js.
¿Cómo obtengo reactividad a este ejemplo?
Parte JavaScript :
var name = "HELLO". //defined as global variable [...] // Handling of click event in three.js if (intersects.length > 0) {for(i = 1; i <= 6; i++) { if(intersects[ 0 ].object.name == 'K' + i ) { //functions for specific parts are wrapped in an object to enable function call based on variable 'i' foo['K_' + i]('K' + i); }} var foo = { K_1: function(i) { name = "foo_ " + i; }, K_2: function() {}, ... }
vue.js Parte:
const app = Vue.createApp ({ data() { return { property: name // object key "property" is set to var "name" } }, template: `<h1> {{ property }} </h1>` }) app.mount('#app')
Para activar la reactividad de vue, debe usar una ref
:
const { ref, createApp } = Vue; var name = ref("HELLO"); var foo = { K_1(i) { name.value = "foo_ " + i; }, }; //the vue app: createApp ({ setup: () => ({ property: name }) template: `<h1> {{ property }} </h1>` }).mount('#app')
Nota: Puede agrupar múltiples referencias en un objeto reactive
, para reducir el modelo:
const { reactive, toRefs, createApp } = Vue; const store = reactive({ name: 'HELLO' someOtherProp: 'whatever', yetAnotherReactiveProp: null // you got the picture }) var foo = { K_1(i) { store.name = "foo_ " + i; // ☝️ no need for `.value` in `reactive`; only in `ref` }, changeSomeOtherProp(val) { store.someOtherProp = val; } } createApp ({ setup: () => ({ ...toRefs(store) }) template: `<h1> {{ { name, someOtherProp, yetAnotherReactiveProp } }} </h1>` }).mount('#app')