0

I want to passing a variable and read a js file from vue. I already testing it with html only it works, just need too declare in the head of html. But how it works in vue?

here's the javascript file that i want to read via vue component, and i want to passing a variable from a component to this file

document.addEventListener('DOMContentLoaded', () => {
  const userGrid = document.querySelector('.grid-user') //done
  const computerGrid = document.querySelector('.grid-computer') //done
  const displayGrid = document.querySelector('.grid-display')
  const ships = document.querySelectorAll('.ship')

  createBoard(userGrid, userSquares)
  createBoard(computerGrid, computerSquares)

  function startSinglePlayer() {
    generate(shipArray[0])
    generate(shipArray[1])
    generate(shipArray[2])
    generate(shipArray[3])
    generate(shipArray[4])

    startButton.addEventListener('click', () => {
      setupButtons.style.display = 'none'
      playGameSingle()
    })
  }

  //Create Board
  function createBoard(grid, squares) {
    for (let i = 0; i < width*width; i++) {
      const square = document.createElement('div')
      square.dataset.id = i
      grid.appendChild(square)
      squares.push(square)
    }
  }

 ........code
})

i already try to use like this

mounted() {
    const plugin = document.createElement("script");
    plugin.setAttribute(
      "src",
      "//api.myplugincom/widget/mykey.js"
    );
    plugin.async = true;
    document.head.appendChild(plugin);
  }```

but the code didn't work. 
*when i only use html file not vue it works. 
Seira
  • 1
  • I see that your code is the same as [This issue](https://stackoverflow.com/questions/45047126/how-to-add-external-js-scripts-to-vuejs-components), but for that issue that's the correct answer. Do you get anything in the console for output? Is the code even being run? Try it with an `console.log("test")` to see if the part is getting mounted properly. – NLxDoDge Jan 10 '23 at 14:44
  • `DOMContentLoaded` event has already fired by the time you add your script. I suggest you take the contents of the handler (the function passed as second argument to `addEventListner`) and place it all inside your component's `mounted`. Should work. – tao Jan 10 '23 at 14:55
  • Could you create a stackblitz with your script and add a link here? https://vite.new/vue – Leif Marcus Jan 10 '23 at 21:04

0 Answers0