javascriptwebpackvue.jsvue-loader

Vuejs: how to manipulate elements using webpack template?


I really don't know how to do this. And I swear I research a lot

enter image description here

this code return null


Solution

  • That element won't exist at that stage because it hasn't been mounted, it needs to be done inside the mounted hook:

    <template>
      <canvas id="canvas-basic"></canvas>
    </template>
    
    <script type="text/javascript">
      export default{
        mounted(){
           console.log(document.getElementById('canvas-basic'));
        }
      }
    </script>
    

    See: see: https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

    And here's the JSFiddle: https://jsfiddle.net/ksg7vyyq/

    You could also use a ref:

    <template>
      <canvas ref="canvasBasic"></canvas>
    </template>
    
    <script type="text/javascript">
      export default{
        mounted(){
           console.log(this.$refs.canvasBasic);
        }
      }
    </script>
    

    Here's the JSFiddle: https://jsfiddle.net/gkc5c1ph/

    Also, you appear to be writing code outside of the Vue object, make sure you look over the docs to understand how to correctly format your code.