What is the best place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code:

const numbers = [1, 2, 3]
new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="number in numbers">
    {{number}}
  </div>
</div>

This code fails with the error message:

[Vue warn]: Property or method "numbers" is not defined on the instance but referenced during render. Ensure the property is reactive by including it in the data option for class-based components. Refer to: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

The warning suggests an attempt to use 'numbers' in a reactive manner. In this case, the intention is for the data to remain static, as indicated by the 'const' declaration.

To resolve the issue, pushing 'numbers' into the instance can be done which resolves the problem:

new Vue({
  el: "#app",
  data: {
    numbers: [1, 2, 3]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js><br /></script><br /><div id="app"><br /><div v-for="number in numbers"><br />{{number}}<br /></div><br /></div>

However, there may be reservations about this approach, considering that 'data' typically stores information prone to change and those changes are reflected in the DOM.

What is the appropriate method of utilizing constant, unchanging data in Vue? (specifically regarding where to declare it)

Answer №1

  1. To access all the necessary data within the template, it must be stored on the Vue instance (either in the `data` or `computed` properties). Every access in the template is done with `this.` prefix and there are no shortcuts around it.
  2. Making your data a part of the Vue instance ensures reactivity. While this is usually beneficial, it can become a performance issue if you have large amounts of static data that will never change. In such cases, you can follow a tip from the documentation and use `Object.freeze()` to make the entire object "non-reactive" yet immutable.
  3. You can customize the reactivity of your data by following this suggestion from Akryum, a Vue core member. This involves creating objects where some properties are reactive while others remain non-reactive. Note that this technique applies to Vue 2, which uses `Object.defineProperty` for reactivity. An update for Vue 3 proxies may be available later.

Option 2 likely offers the most suitable approach for your specific scenario...

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

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

How can I send an array of date and time values from a Vue.js component to an ASP.NET Core API?

Here is my API code snippet: [HttpGet("/GetBusinessDaysWithPublicHolidayDates/")] public int GetBusinessDays(DateTime startDate, DateTime endDate,[FromQuery] IList<DateTime> publicHolidays) { var noOfDays = _dayCalculatorService.Busines ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

What is the maximum character limit for the JQuery validation plugin?

Currently, I am utilizing the JQuery validation plugin in my project. My goal is to set a maxlength for one of the fields. Here's an example of how it can be done by defining rules externally: rules: { Message: { required: false, maxLe ...

Tips for utilizing the beforeEach feature in node-tap?

Could someone please demonstrate how to utilize the beforeEach function? For more information, visit: . I am particularly interested in seeing an example using promises, although a callback version would also be appreciated. Below is a successfully functi ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamically, meaning it is empty when t ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...

Guide to automatically sending users to a subdomain depending on their IP address location

Currently, my website is built using Node Express and I have a specific requirement. I want to redirect users to different subdomains based on their current location. For example, if a user in Singapore accesses site.com, they should be redirected to sg. ...

`HTTP Streaming with Axios in a Node JS Environment`

I am currently facing an issue while attempting to stream price data via HTTP (I'm surprised they aren't using websockets..). I usually use axios for making REST API requests, however, I am struggling to handle 'Transfer Encoding': &apo ...

Tips for managing mouse over events in legends on highcharts

I have successfully implemented mouseover/mouseout event handling for donut slices. Please review my code below: http://jsfiddle.net/nyhmdtb8/6/ Currently, when I hover over a slice, it highlights that slice and greys out all others. Is it possible to ac ...

What is the best way to conduct a conditional check across all subsequent visible rows of a table?

When a user clicks inside the text input field and presses either the down or up arrow keys, my JavaScript function is triggered. The purpose of this functionality is to search table values and allow the user to select one by pressing the arrow keys. Every ...

Error in Serializer when validating data with Vue3 frontend and Django backend

I built a Vue front end that gathers user data and files, then uses Axios to POST it to a Django Rest Framework endpoint. Below is the function code: import { ref } from "vue"; import axios from "axios"; const fields = ref({ audie ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...