这是在 Vue.js 组件中设置 id 的正确方法吗?
Is that the right way to set an id in Vue.js component?
我正在尝试将 Phaser 3 与 Vue.js2 集成。
我的目标是创建一个与游戏相关的 Vue.js 组件 canvas。
我最初的解决方案是:
<template>
<div :id="id">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
id: null,
game: null
}
},
mounted () {
this.id = 'game' + this._uid
var config = {
parent: this.id,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>
此代码将游戏 canvas 附加到我的模板。但令我惊讶的是它只起作用 'sometimes'.
经过数小时的调试,我发现在实例化我的新游戏时,DOM 中的 div 元素未使用 ID 进行更新。
于是想出了在beforeMount()方法中实例化id的解决方法如下:
<template>
<div :id="id">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
id: null,
game: null
}
},
beforeMount () {
this.id = 'game' + this._uid
},
mounted () {
var config = {
parent: this.id,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>
可以用,但我想知道是否有更简单优雅的解决方案?
将 Phaser.Game 集成到应用程序中的一个更好的解决方案是直接将配置传递给 HTML 元素,a configuration supported by Phaser.Game.
要在 vue 中获取对 HTML 元素的引用,您可以使用 refs,这些基本上是 id,但对组件本身而言是本地的,因此不存在产生冲突的风险。
<template>
<div ref="myDiv">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
game: null
}
},
mounted () {
var config = {
parent: this.$refs.myDiv,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>
我正在尝试将 Phaser 3 与 Vue.js2 集成。
我的目标是创建一个与游戏相关的 Vue.js 组件 canvas。
我最初的解决方案是:
<template>
<div :id="id">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
id: null,
game: null
}
},
mounted () {
this.id = 'game' + this._uid
var config = {
parent: this.id,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>
此代码将游戏 canvas 附加到我的模板。但令我惊讶的是它只起作用 'sometimes'.
经过数小时的调试,我发现在实例化我的新游戏时,DOM 中的 div 元素未使用 ID 进行更新。
于是想出了在beforeMount()方法中实例化id的解决方法如下:
<template>
<div :id="id">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
id: null,
game: null
}
},
beforeMount () {
this.id = 'game' + this._uid
},
mounted () {
var config = {
parent: this.id,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>
可以用,但我想知道是否有更简单优雅的解决方案?
将 Phaser.Game 集成到应用程序中的一个更好的解决方案是直接将配置传递给 HTML 元素,a configuration supported by Phaser.Game.
要在 vue 中获取对 HTML 元素的引用,您可以使用 refs,这些基本上是 id,但对组件本身而言是本地的,因此不存在产生冲突的风险。
<template>
<div ref="myDiv">
</div>
</template>
<script>
import Phaser from 'phaser'
export default {
data () {
return {
game: null
}
},
mounted () {
var config = {
parent: this.$refs.myDiv,
type: Phaser.CANVAS
}
this.game = new Phaser.Game(config)
....
}
}
</script>