Search code examples
javascriptvue.jsvuejs3cdn

How can I get HTML element when importing Vue via CDN?


I'm using Vue 3.0.2 in my project, loaded via CDN as follows:

<head>
 ...
  <script src="https://unpkg.com/vue@3.0.2"></script>
</head>

How can I access an HTML element in my Vue component when importing the library via CDN? I want to do the equivelant of what would be document.getElementById('element') in plain JS.

Related posts on here suggest that calling $this.el.querySelector should work for this, however I don't have access to that function. I suspect due to importing Vue via CDN?

My component looks as follows...

const app = Vue.createApp({
        data() {
            return {
                // data members.
            }
        },
        methods: {
            // method definitions.
        } });

app.mount('#app')

Thanks for any advice!


Solution

  • Try something like this

      <script src="https://unpkg.com/vue@3.0.2"></script>
      </head>
      <body>
        <div id="app">
          <h1>{{ data }}</h1>
          <input type="text" ref="input">
          <button @click="log">LOG</button>
        </div>
        <script>
          const app = Vue.createApp({
            data() {
              return {
                data: 'any'
              }
            },
            methods: {
              log() {
                console.log(this.$refs.input.value)
              }
            }
          });
    
          app.mount('#app')
        </script>