In Vue, using the ref function does not automatically result in the creation of a

CustomPage.vue:

<template>

  <div>
    <CustomChild :cat = "this.parentCat"  />

    <div v-on:click="this.changeName" id="change-button">
      Change Parent Cat name
    </div>
  </div>

</template>

<script>
 import CustomChild from "@/components/CustomChild";
 export default {
  components: {CustomChild },

  methods:  {
    changeName()  {
      this.parentCat.name = "Changed First Name";
      alert("Changed!");
    }
  },

   data() {
     return {
       parentCat: {
         name: "First Cat"
       }
     };
   },
};

</script>

<style>

#change-button  {
  margin: 2em;
  padding: 1em;

  background-color: blue;
}

</style>

CustomChild.vue:

<template>

  <div>{{this.superiorCat.name}}</div>

</template>

<script>
import {ref} from 'vue';

export default {
  name: "CustomChild",

  props:  {
    cat: Object
  },

  data() {
    return {
      superiorCat: Object
    };
  },

  created() {
    this.superiorCat = {};
    this.superiorCat.name = ref(this.cat.name);
  }
};
</script>

The display before the blue button is clicked:

https://example.com/uBihf.png

The information for the CustomPage: https://example.com/6baBx.png The details for the CustomChild: https://example.com/D7PHC.png

The names of parentCat in CustomPage and superiorCat in CustomChild are identical.

After clicking the blue button, the page output remains unchanged. The information updates as follows:

The details for the CustomPage: https://example.com/3K5XF.png The details for the CustomChild: https://www.example.com/muWmg.png

Therefore, once the button is clicked, the cat property in the CustomChild component reflects the modification, while the superiorCat data does not, even when using ref.

How can I ensure that superiorCat.name also becomes reactive? Without resorting to applying watch on the cat property.

Answer №1

The Composition API is designed to replace the options API in Vue. While it is possible to use them together, doing so can lead to confusing and undocumented situations. In this case, using ref is unnecessary as the data state is already reactive in Vue 3. References are automatically unwrapped when used within reactive objects.

In order to synchronize a reactive property with another property, a computed or watcher function is required. If betterDog does not need to change properties independently from parentDog throughout the child component's lifespan, there is no need for it to be included in the component state or have a watcher:

computed: {
  betterDogName() {
   return this.dog.name
 }

Having betterDog: Object is technically incorrect as data should return an initial value, whereas Object is a function. However, this error does not impact how it functions in this 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

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Using Three.js to create smooth rotations for objects

I have a logo in .obj format that I am loading onto a canvas using three.js. The logo is an integral part of the website's loading section that I am currently developing. Within this section, there is a 'Click to Enter' button. My goal is fo ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Encountered an unexpected identifier error while executing a Nuxt.js project

I am utilizing the following technologies: Node.js version 6.14.2 NPM version 6.0.1 Ubuntu 16.04 Whenever I attempt to execute a project, I encounter the following error message: npm run dev node_modules/nuxt/lib/core/module.js:14 async ready( ...

What is the process for incorporating elements into Particles.js within Nuxt 3?

Adding particles.js to my nuxt 3 project posed a challenge. I utilized https://github.com/Joepocalyptic/nuxt-particles, but unfortunately, whenever I added an element within <NuxtParticles>, the element did not show up. // app.vue <template> ...

Angular directive: Exploring the disparities between controller scope and link function scope

As I delve into the world of Angular directives, the concept of scope is proving to be quite challenging for me. Let's consider a custom directive named parentDirective, which has both a controller property and a link property: angular.module("app"). ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

Guide to substituting the index value with the user's specific choice

Let's simplify this. Suppose I have a list in my ng-repeat 1. A & index[0]<br> 2. B & index[1]<br> 3. C & index[2]<br> 4. D & index[3]<br><br> and there is an input field where the user can priorit ...

Verify if an Ajax request has been made

I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the Acti ...

Navigating through search results on an XML page using jQuery

Context: I am currently facing a challenge involving the integration of Google search outcomes into a webpage I'm constructing. These findings are presented in XML format. My current approach to importing the XML is as follows: if (window.XMLHttpReq ...

How can we utilize data retrieved from Mongodb in Express and pass it to a Jade view using the res.render function?

Within my node/express application, I need to pass data retrieved from mongoose to my jade view. The code below in routes.js accomplishes this task: app.get('/newrequest', function (req, res) { Account.find({}, function (err, data) { ...

What is the reason behind Istanbul's code coverage reporting a switch statement as uncovered even though all conditional paths are covered?

Within my node.js application, there is a class that includes a getter method with a significant switch statement. Rather than the simple example provided below, this switch statement contains numerous unreleased product-specific values replacing 'a&a ...

Encountered Node.js & MySQL error: 1251 - Client not able to support authentication protocol requested by server. It is recommended to upgrade MySQL client for resolving this

I currently only have the following code snippet: const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'root', 'passwd', { host: 'localhost', dialect: 'mysql', ...

The Naming Convention for NPM Scripts

In my package.json, I have a script that looks similar to this: { ... scripts: { ... "testdb:e2e": "TESTDB_ENV='...' gulp mocha:e2e:backend && gulp mocha:e2e:frontend" } ... } I am interested in adding a s ...

javascript inquiry about if statements

function checkValidity() { startChecked = false; finishChecked = false; alert("startChecked: " + startChecked); alert("finishChecked: " + finishChecked); if (document.dd.start.checked.length == undefined || document.dd.finish.checked. ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Update a variable in one component class using another component

My Hue class in a component contains a variable that I'm trying to modify: export default class Hue extends Component { state = { toggleState : false, toggleWhite : false } render(){...} ... } Within this component, I can chang ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...