Data binding in Vue does not function properly within functional components

Clicking the button will cause the number n to increase, but the UI will display it as constant 1.

<script>
let n = 1
function add() {
  console.log(n)
  return ++n
}
export default {
  functional: true,
  render(h, ctx) {
    return (<div>
      <h1>{n}</h1>
      <button onClick={add}>click</button>
    </div>)
  }
}
</script>

Answer №1

Purposeful Functionality

This demonstrates the intended functionality of functional components, highlighting their efficiency. As stated in the documentation:

...we can designate components as functional, indicating they are stateless (lack reactive data)

Because functional components are essentially functions, their rendering process is cost-effective.

Clarification

The significance of this-- and why n does not exhibit reactivity-- lies in n lacking observable properties and not being subjected to dependency management/watching. The absence of overhead from dependencies contributes to the performance boost seen with functional components. Choosing speed means sacrificing observability, representing a favorable tradeoff when it's unnecessary. Opting for a non-functional component becomes advisable if observability is required.

Next Steps

Your decision could involve using a traditional non-functional component or pondering the feasibility of dividing your functional component further to isolate reactive parts into a non-functional subcomponent.

Additional Considerations

If you manually introduce observability to your functional component, the desired behavior can be attained; however, leveraging a non-functional component would be more appropriate. Pay attention to the usage of observable:

import Vue from 'vue';
let state = Vue.observable({n: 1});

function add() {
  console.log(state.n)
  return ++state.n
}

export default {
  functional: true,
  render(h, ctx) {
    return (<div>
      <h1>{state.n}</h1>
      <button onClick={add}>click</button>
    </div>)
  }
}

(Note: While render functions are common in normal components too, this information clarifies that functional components aren't obligatory for utilizing render functions.)

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

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

XSL is the key component in creating a unique Custom Slider that remains stationary

I am currently working on a jQuery slider project and I am encountering an issue with getting the images to slide properly. The arrows seem to be functioning as expected, indicating that the necessary classes have been added, but the actual sliding action ...

What is the most effective method to verify the visibility of an element hidden by v-show when using testing-library in Vue?

When working with Vue and the testing-library, checking for the presence of an element in the DOM is straightforward. For instance, if the v-if condition for the element is set to false: element = screen.queryByTestId("my-element") expect(element).toBeNul ...

Setting the texture for a loaded glb model using Three.js

After successfully loading a basic glb model created in SketchUp using Three.JS, I encountered an issue with displaying text on the model. The model includes a group identified as Text. Despite being able to load and visualize the model correctly in Three ...

Step-by-step guide on retrieving data from E-goi with REST API in Google Apps Script

Looking to extract data from the e-goi API, I found a .jar file in their documentation. Unfortunately, there are no examples provided for the REST API, leaving me unsure of how to access it directly. As I'm still new to programs like this, I could rea ...

The attempt to perform a Diffie-Hellman key exchange between Python and Node has hit a roadblock, as an error stating that

Currently, I am attempting to establish a DH key exchange between a Python 3.6 client and a Node server deployed in a Docker container with the latest node image (Node version: v13.10.1). On the client side, I am utilizing the cryptography.io library (v2. ...

Tips for extracting a website's dynamic HTML content after AJAX modifications using Perl and Selenium

When dealing with websites that utilize Ajax or javascript to display data, I'm facing a challenge in saving this data using WWW::Selenium. Although my code successfully navigates through the webpage and interacts with the elements, I've encounte ...

Display issue with ThreeJS cube

Currently, I'm delving into the world of ThreeJS and decided to incorporate the library into my existing NextJS project. My goal was simple - to display a cube on the front page. However, despite my best efforts, nothing seems to be appearing on the s ...

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

Resetting tests in Vue using vitest and testing-library: A complete guide

Currently, I am experimenting with testing Vue components using a combination of Vue, testing-library, and vitest. The specific component I am working on utilizes vee-validate for validation. TheLogin.vue <template> <div class="container ...

Link the values of mongoose array to a distinct identifier

This question may come across as vague, but I'll do my best to explain it clearly. Just a heads up, I'm relatively new to working with mongoose :) So, I have this mongoose schema where different values are stored for each user: let userSchema = ...

Retrieve the input field value using JavaScript within a PHP iteration loop

I've implemented an input box inside a while loop to display items from the database as IDs like 001,002,003,004,005 and so on. Each input box is accompanied by a button beneath it. My Desired Outcome 1) Upon clicking a button, I expect JavaScript t ...

Obtaining cookies from a separate domain using PHP and JavaScript

Imagine you have a cookie set on first.com, called "user". Now, the goal is to retrieve that cookie on second.com using JavaScript and AJAX. Unfortunately, it's not working as expected and you're receiving xmlHttp.status=0. Here is a sample code ...

Evaluating Vue.js Watchers using Jasmine

I want to write a test for a VueJS watcher method, in order to verify if it's being called. The watcher method in my component is structured like this: watch: { value: (newValue, oldValue) => { if (newValue.Status === 'Completed') ...

Display the data returned from a computed property PromiseResult using VueJS

After calculating the property shown below, it will output res, which is a Promise object. The reason I cannot place this script inside the created() or mounted() hook is due to the fact that this.selectedObject is null at that time. I am satisfied with t ...

How to incorporate text into the white circle object using three.js

View the current state of my project on this JS Fiddle. I am looking to incorporate rotating text, whether in 3D or 2D. The text should rotate in sync with the white circle. I am open to any method that achieves the desired outcome. Below is the provided c ...

Enhancing Pinia setup stores with custom getters, setters, and actions for improved reusability

If we think about a Pinia setup store that has a basic set of state, getters, and actions in place: export const useBaseStore = defineStore('base-store', () => { const name = ref<string>(''); const age = ref<number>(1 ...

the power of using keywords and prototypes

Greetings! I am currently delving into the realm of JavaScript, hailing from a C++ background. The transition has proven to be quite perplexing for me. Below is a snippet of code that I have been troubleshooting: var someArray = []; nameCompare = function ...

What is the method for showcasing an array using AngularJs in my specific scenario?

I have an array in JavaScript structured like this: var data = [ 2005 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 2006 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 200 ...