What are some best practices for managing object-level variables in TypeScript and Vue.js?

Uncertain about the optimal approach, I am looking to create a component and leverage some object level variables. Consider the example below:

import Vue from "vue"
import * as paper from "paper"

export default Vue.extend({

    template: `
        <div class="chart-container" ref="chart-container">
            <canvas ref="canvas"></canvas>
        </div>
    `,

    mounted: function() {

        this.$nextTick(function() {
            let canvas = this.$refs["canvas"] as HTMLCanvasElement
            let chartContainer = this.$refs["chart-container"] as HTMLDivElement
            // Throws errors since there is no definition for the variable paperScope
            this.paperScope = new paper.PaperScope()
            this.paperScope.setup(canvas)
        })
    },

    methods: {
        resizeCanvas(): void {
            let chartContainer = this.$refs["chart-container"] as HTMLDivElement
            let width = chartContainer.clientWidth - 30;
            let height = chartContainer.clientHeight - 30;
            // Aim to access the class-level variable in declared methods
            this.paperScope.view.viewSize = new paper.Size(width, height)
        }
    }
})

I wish to establish an object level variable paperScope that can be accessed across methods without storing it in data, as there is no need for vuejs monitoring. Is there a way similar to

this.$privateVariables["paperScope"] = paperScope

that can serve this purpose?

Currently contemplating creating a type definition that extends the vue one, incorporating something like $privateVariables. Interested to know if there is an existing or more efficient method to achieve what I am aiming for.

Answer №1

I prefer not to store these variables in the data, as they don't require monitoring by vuejs.

If you wish to have non-reactive variables like this, you can utilize $options for storage. I came across this technique in this specific issue comment.

Visit this link for a demonstration

HTML:

<div id="app">
  <p>{{ message }}</p>
  <button @click="updateText">
    update
  </button>
</div>

Vue component:

new Vue({
  el: '#app',

  privateVariable: 'Thanks Vue.js!',

  data() {
    return {
      message: 'Hello Vue.js!'
    };
  },

  methods: {
    updateText() {
      this.message = this.$options.privateVariable;
    }
  }
})

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

Angular JS: How to dynamically add and remove checkboxes in ng-repeat?

Currently, I have successfully implemented a Miller column using Angular and Bootstrap. To view the functionality in action, you can check out the code snippet at this link. In the second column of my setup, clicking on a word opens up the third column. ...

Looking to set an object value as optional in JavaScript?

Hello, I am currently in the process of developing a web application using ReactJS with Auth0 for user authentication. In order to update user information on my backend, I am utilizing state to store the necessary data. My challenge lies in allowing eith ...

Create a copy of an element without altering the original

Currently, I am attempting to create a duplicate of a class and ensure that it remains unaffected when the original is altered. So far, I have tried: $(".newclass").addClass("oldclass"); However, this method does not copy the content. var _elementClone ...

Having trouble getting Tailwind CSS utility classes to work with TypeScript in create-react-app

I have been struggling to troubleshoot this issue. I developed a React application with TypeScript and integrated Tailwind CSS following the React setup guidelines provided on the official Tailwind website here. Although my code and configuration run succ ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

Using Vue to transfer data from one component to another by passing props to an element

I'm currently exploring a method to pass a Vue prop to the a tag within the second component. It needs to be a dynamic prop, so I cannot specifically import it into the component. First fragment <script> export default { name: 'first&apo ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Tips for recognizing when Vuetify's v-autocomplete has reached the final scrolled item

I am working with a Vuetify v-autocomplete component and I need to implement a feature where I can detect when the user reaches the last item while scrolling, in order to load more items without the user having to manually type for search: // component.vue ...

Issue encountered when trying to render Vue.js file with the view instance "new Vue()"

When working with vue.js and rendering a vue page, I encountered the following error: Error "Cannot GET /KForm" My code in main.js is as follows: import * as componentBase from "@app/app_start" import Form from "@views/Form/Form.vue" import KForm from ...

Can JavaScript be used to update/override Prototype version 1.4 to version 1.7 on a different website?

(I'm uncertain about the best way to phrase this question, feel free to make changes). I am in the process of embedding a JS widget onto a different website that is using Prototype.js Version 1.4. I have incorporated jQuery into my widget and have it ...

Tips for handling timeouts when a connection fails to establish

Is there a default timeout value in the socket.io API that triggers after multiple connection attempts fail? In my application, I am trying to connect to a Node.js server using socket.io. If the connection is not established or unreachable, I want to recei ...

Errors are thrown when utilizing hydration with RTK Query

Looking for a solution with my local API and RTK Query, I've encountered an issue when implementing server-side rendering (SSR). Here's the code snippet I'm working with: const api = createApi({ reducerPath: 'data', baseQuery: ...

Is there a problem with AngularJS $state.go() not emitting $stateChangeSuccess?

In my scenario, I have controllers A and B located in different states. When I trigger $state.go('state_b');, Angular switches to state state_b and loads controller B. However, what surprises me is that I do not receive $stateChangeSuccess in my ...

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Retrieve the id within the parentheses for each checkbox that is checked and re-check each time a checkbox is selected using Kendo UI

Working with the tricky kendo-ui has made adding selectors quite challenging; however, my current task involves simply obtaining the inner contents of the id selector upon clicking an input checkbox element. Specifically, I need to extract the text between ...

Javascript/Jquery - Eliminating line breaks when transferring text to a textarea by copying and pasting

Is there a method to paste text into a textarea that will automatically remove any line breaks or whitespaces? For instance, if I copy the following text and paste it into the textarea: abcdef, ghijkl, mnopqrs I would like it to appear in the textarea as ...

What steps can be taken to stop Internet Explorer from caching Ajax requests in Angular2 using TypeScript?

Imagine a situation where a user has 10 points. When they click a button, an ajax call is made to the server to update the user's points after they have been used. The server should send back 9 points, which is functioning correctly on all browsers ex ...