Can you explain the distinctions between using this['key'] and $data['key'] in the context of v-model?

Take a look at the snippet below, which includes three demos. The first two demos are functioning correctly (v-model is working fine).

However, in the last demo, when you type something into the <input>, you will notice that this['test 1'] does not get updated. The value of

<h2>Name:<span>{{this['test 1']}}</span></h2>
always remains as the initial value.

It appears that v-model binds a clone to this['test 1']. In this scenario, we need to use $data['test 1'].

Does anyone know what is causing these differences?

app = new Vue({
  el: "#app",
  data () {
    return {
    'test': "Cat in Boots",
    'test 1': 'Snow White'
    }
  },
  methods: {
    testCase1: function(){
      this['test'] = 'I am Cat in Boots' //works
      this['test 1'] = 'I am Cat in Boots' //works
    }
  }
})
span {
  background-color:green
}

a {
  color:red
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4828191b4c6dac1dac5c2">[email protected]</a>/dist/vue.js"></script>
<div id="app">
    <button @click="testCase1()">Test Case 1</button>It will change the data successfully.
    <h2>Name:<span>{{test}}</span></h2>
    <input v-model="test">
    <h2>Name:<span>{{$data['test 1']}}</span></h2>
    <input v-model="$data['test 1']">
    <h2>Name:<span>{{this['test 1']}}</span></h2>
    <input v-model="this['test 1']"><a>Type something in this input, the name will not be changed.</a>
</div>

Answer №1

When working with templates, ensure to avoid using this since it does not point to the template's component. Instead, make use of $data in such scenarios.

Answer №2

The main issue lies in:

According to Vue's creator, this will undergo changes in the compiled template depending on the function scope you are currently in.

Hence, it is advised to avoid using this in the template.

To learn more about this issue, refer to the feedback provided by Vue's creator at this link

You can also examine the source code for directive->model.js on Github.

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

Ordering AngularJS by property name with spaces

While working with the MEAN stack and jade, I encountered an issue with AngularJS when using ng-repeat, ng-click, and orderby to sort columns in a table. Everything was working well until I tried sorting by a column named "To Do" which contains a space. Th ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

When attempting to fetch data with a dynamic URL in next.js, the error message "undefined is returned

While fetching data on my main page everything works as expected. However, when trying to fetch data in another folder using the same code but with a dynamic URL, I encounter an error when attempting to use methods on an array. Interestingly, when I consol ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

Combining elements from a string array to create a hierarchical object in JavaScript

I need assistance with merging values from an array into a predefined nested object. Here is an example of the array with values, ['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27'] The object that needs ...

Gruntjs Live Reload is actively monitoring for changes, yet fails to refresh the page

Check out my Gruntfile.js here Also, take a look at my package.json here I ran npm install in the main directory of my workspace (using WAMP) and it created a node_modules folder along with several subfolders. After navigating to the directory c:\w ...

Incorporate HTML elements into a React component

Is there a way to render (move) a DOM element into a React Component? I am facing a situation where I have integrated a third-party script into my React project (such as incorporating a live chat widget with a script). This script generates a DOM node when ...

Data is not being refreshed by Ajax

In my forum, users are only allowed to edit and delete their own comments. I have set up an "edit" button that opens a modal when clicked, giving the user access to the data they submitted before. I've written an ajax function to target these fields a ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Is there a way to insert a row into a datatable without needing to perform an Ajax reload or using the

When using row.add(…) on a datatable, I encounter an issue where it refreshes via an ajax call when draw() is activated. This leads to the new row not being visible because the data is reloaded from the database. The UX flow behind this scenario is as f ...

A complex valueOf function in Javascript

What is the purpose of using ({}).valueOf.call(myvar)? This expression converts any value to an object. If the input is already an object, it remains unchanged; however, if it is a primitive type, it gets converted to an instance of a wrapper type. I ...

Error message: No instance of an app record ID was found in Vue.js Console

Occasionally, an unfamiliar error message pops up in the console of my Vue.js application and I'm unsure about its cause. I am currently running Vue 2.6.11 alongside oidc-client and a vue sidebar menu. Here are the details I can share: https://i.sst ...

Struggling with the proper state updating in React hooks when using dynamic naming conventions?

I am currently working with a react component that handles login requests to my server. This component is housed within a modal using Material UI. <TextField onChange={handleChange} autoFocus name="email" ...

Error in Nuxt/TypeScript: Unable to retrieve this - TS2339: Property 'XXX' is not found on type

I encountered an issue while working with Nuxt.js and TypeScript. In my project, I rely on dependencies such as axios or nuxt-i18n. As an example, let's focus on Axios. I followed the configuration outlined in the official documentation for nuxt/axios ...

Tips on properly breaking the line with vue-typer while ensuring words remain intact

I'm currently using vue-typer, and I've noticed that it adjusts on the screen based on available space. However, I've run into an issue where depending on the screen size, vue-typer breaks words in unexpected places. My goal is to have the w ...

Is there a way to utilize a variable as a key within an object?

Can this be done? Take a look at a practical example from the real world: var userKey = "userIdKey"; chrome.storage.sync.set({ userKey: "Hello World" }, function () { chrome.storage.sync.get(userKey, function (data) { console.log("In sync:", ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Error: The XML parsing in ASP failed to find a root element at the specified location

When clicking the button, I have jQuery/Ajax code that is supposed to pass the value of a selected radio button to a controller action and open a detail page. However, I am encountering an error. When using Mozilla Firefox, the console displays: XML Par ...