简体   繁体   English

如何将 vue.js 数据同步到全局 javscript 变量

[英]How to sync vue.js data to global javscript variable

I am currently working on an application with three.js and vue.js .我目前正在处理three.jsvue.js的应用程序。

When I click on the 3D model a function gets triggered where the name of the clicked part of the model is set in the variable "name" which then should be rendered by vue.js.当我单击 3D model 时,将触发 function,其中 model 的单击部分的名称设置在变量“名称”中,然后应由 vue.js 呈现。

On pageload the inital value of "name" in this example HELLO gets rendered.pageload时,本例HELLO中的“name”inital值被渲染。 But when I click on the model the variable "name" gets updated but not the data variable "property" in vue.js.但是当我点击 model 时,变量“name”得到更新,但 vue.js 中的数据变量“property”没有更新。

How do I get reactivity to this example?我如何获得对此示例的反应?

JavaScript Part : 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 Part: vue.js 部分:

const app = Vue.createApp ({
    data() {
        return {
            property: name // object key "property" is set to var "name"
        }
    },

template: 
    `<h1> {{ property }} </h1>`
})

app.mount('#app')

To trigger vue's reactivity you have to use a ref :要触发 vue 的反应性,您必须使用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')
    

Note: You can group multiple refs into one reactive object, to reduce the boilerplate:注意:您可以将多个 refs 组合成一个reactive object,以减少样板文件:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM