The component is unable to access VueJS references

Below is a simplified version of the code I am working with:

<html>
    <head>
        <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <Dial style="width: 120px; height: 120px;" v-model="src_value"></Dial>
        </div>

        <script>
            Vue.component('Dial', {
                template: '<canvas ref="dial_canvas"></canvas>',
                data: function () {
                    return {
                        value: 0,
                        centre: { x: 0, y: 0 },
                        canvas: null
                    }
                },
                props: ['value'],
                mounted: function() {
                    console.log(this.$refs.dial_canvas);
                },
                render: function() {
                    // To be implemented.
                }
            });

            var app = new Vue({
                el: '#app',
                data: {
                    src_value: -1
                },
                created() {
                }
            });

        </script>
    </body>
</html>

Upon running this code and checking the console log, this.$refs.dial_canvas appears to be undefined.

I have gone through several related questions. One question and another question both suggest that attempting to access $refs (or $el) within created() instead of mounted() could be the issue, but that doesn't seem to be the case here.

I have come across multiple articles discussing the use of references in components, however, they all involve ".vue" files and utilize complex syntax for component imports - which doesn't align with my goal. It seems like they rely on server-side processes that I want to avoid. My aim is to keep the web server setup as straightforward as possible, solely serving plain text files.

In order to make my component reusable and display distinct values, how can I access the refs in my component while keeping it simple?

P.s. Prior to some modifications, $el also used to reference the <canvas> element, yet now it too returns as undefined.

Answer №1

As pointed out by @skirtle, it is not possible to have both a render function and a template in Vue. Interestingly, I discovered that having an empty render function resulted in Vue replacing the element with an empty comment.

Moreover, I encountered issues when using capital letters in the component name.

To resolve this issue, I decided to replace my render function with a method:

methods: {
    setValue: function(value) {
        this.value = value;
        // TODO: Implement canvas drawing logic here.
    }
},

I also included a ref in the template entry and updated the value using the ref to access the component. By utilizing the new setValue method, I was able to update the internal value and redraw the canvas accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to assign the chosen option from a dropdown list to an input field in Vue 3?

I am working with a list that is returned from an API request. I have a text input field where I can search for items in the list, and the results are displayed dynamically as I type. My goal is to be able to select an option from the list and display the ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...

Feeling grateful: Enable scroll functionality for a log widget

I am currently utilizing the Blessed library to create a dashboard within the terminal. My issue lies in making the log widget scrollable. Despite implementing the code below, I am unable to scroll using my mouse wheel or by dragging the scrollbar: var l ...

How can Sequelize handle multiple foreign keys - whether it be for one-to-many relationships or many-to-many relationships

I'm working on a project with two tables: users and alerts. Users should have the ability to upvote and downvote on alerts. Here are the model definitions: Alert module.exports = function(sequelize, DataTypes) { var Alert = sequelize.define("al ...

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

Holding off on routing the pathName through the router until the next-page-transitions have been completed

In my current setup, I have two distinct elements at play. Using the code snippet below: className={router.pathname.startsWith("/pagename") ? "menu-active" : ""} I am able to apply the menu-active class to the pagename naviga ...

Conceal the div with ID "en" if the value matches $en

Looking for assistance with language settings on my page. I have a menu where I can select English, Croatian, or German. Below is the code to manage language changes: <?php class home_header_language { protected $_DBconn; ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

What are some solutions for resolving the issue of a neutralino white screen?

After setting up a new neutralino js application, I encountered an issue where upon running it with the 'neu run' command, all I see is a blank white screen. I tried using the CheckNetIsolation.exe ... command to troubleshoot the problem, but unf ...

Component inexplicably rendering multiple times

After encountering multiple re-renders in my code, I decided to comment out every line and discovered that the constant definition was causing the issue: const MyComponent = () => { console.log('render') // logs 4 times const myRef = useR ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

"Encountering an access denial error while trying to load a texture in JavaScript using Three.js: Restricted

I'm having trouble loading a texture in my JavaScript program using Three.js. Everything seems to be working fine with rendering a few objects, but as soon as I add the following code: var grzybSkin = THREE.ImageUtils.loadTexture('grzybuv.png&a ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...