I program a little chess-like game with Vue
I am trying to instanciate new Pieces with data.
Basicly I want do this (expressed in a different Language):
array.add(new Piece(data))
currently I'm doing this:
const piece = {
name: 'piece',
template: "<div> ... "
data: function () {
return {
id: null,
//data
isInit: false,
}
},
mounted: function () {
game.register(this)
},
methods: {
isInstanciated: function () {
return this.isInit
},
init: function (id, data) {
this.isInit = true
this.id = id
//initialize, etc
}
}
const app = {
name: 'App',
components: {
piece
},
data: function() {
return {
pieceClassArray: [],
pieceObjectArray: [],
}
},
methods: {
register: function (pieceInstance) {
this.pieceObjectArray.push(pieceInstance)
},
instanciatePiece: function (id, data) {
this.pieceClassArray.push(piece)
let that = this
setTimeout(function () {
for (let pieceInstance of that.pieceObjectArray) {
if (pieceInstance.isInstanciated() === false) {
pieceInstance.init(id, data)
break
}
}
}, 50);
},
}
const game = Vue.createApp(app).mount('#app')
// !!!!somewhere in the html !!!!
<piece v-for="piece in pieceClassArray"></piece>
Explanation of my ridiculous code:
I am starting with the instanciatePiece() function
this.pieceClassArray.push(piece) makes a new component due to this wierd Vue functionality <piece v-for="piece in pieceClassArray"></piece>
after that the piece.mounted calls game.register(this)
which collects the new Object reference and stores it in a pieceObjectArray
-> in a time delayed function is then iterated over pieceObjectArray to find new, unitialized Pieces to initialize with the given data
Its working, but I am very sure, that I am using Vue wrong
How should a Component be instanciated in Vue3 ?
When i tried instanciating with Vue.createApp(piece) i couldn't pass any data, and when i created the second one, both diappeared for unknown reasons