Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Instanciate new Component in Vue 3 with Data

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

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda