如何将 vue.js 数据同步到全局 javscript 变量
我目前正在使用 two.js
和 vue.js
开发一个应用程序。
当我单击 3D 模型时,会触发一个函数,其中模型的单击部分的名称设置在变量 "name" 中,然后该变量应由 vue.js 渲染。
在页面加载
上,本例中的“name”的初始
值HELLO被渲染。但是,当我单击模型时,vue.js 中的变量 "name" 会更新,但数据变量 "property" 不会更新。
我如何获得对此示例的反应?
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 部分:
const app = Vue.createApp ({
data() {
return {
property: name // object key "property" is set to var "name"
}
},
template:
`<h1> {{ property }} </h1>`
})
app.mount('#app')
I am currently working on an application with three.js
and vue.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.
On pageload
the inital
value of "name" in this example HELLO gets rendered. But when I click on the model the variable "name" gets updated but not the data variable "property" in vue.js.
How do I get reactivity to this example ?
JavaScript Part :
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 :
const app = Vue.createApp ({
data() {
return {
property: name // object key "property" is set to var "name"
}
},
template:
`<h1> {{ property }} </h1>`
})
app.mount('#app')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要触发 vue 的反应性,您必须使用
ref
:注意:您可以将多个 ref 分组到一个
reactive
对象中,以减少样板:To trigger vue's reactivity you have to use a
ref
:Note: You can group multiple refs into one
reactive
object, to reduce the boilerplate: