是否可以访问 Vue.js 数据属性的值并将其分配给该属性 Is this[[attributeName]] = "x";在 Vue.js 方法中有效吗?

问题描述 投票:0回答:1

我写了以下不起作用的内容,我想知道是否可以在此 Vue 代码中遵循 DRY 原则:

`const app = Vue.createApp({
    data(){
        return {
            firstInputBoxTextValue: "",
            secondInputBoxTextValue: ""
        };
    },
    methods: {
        showAlert(){
            alert("Button has been clicked..!");
        },
        updateInputBoxText(event,inputBoxTextIdentifier)
        {
            this[[inputBoxTextIdentifier]] = event.target.value;
        }
    }
});
 
app.mount("#assignment");
 
 
//////////////////////////////////////
 
 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue" defer></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Events</h1>
    </header>
    <section id="assignment">
      <h2>Event Practice</h2>
      <!-- 1) Show an alert (any text of your choice) when the button is pressed -->
      <button v-on:click="showAlert">Show Alert</button>
      <hr />
      <!-- 2) Register the user input on "keydown" and output it in the paragraph (hint: event.target.value helps) -->
      <input type="text" v-on:keydown="updateInputBoxText($event,firstInputBoxTextValue)"/>
      <p> OUTPUT {{firstInputBoxTextValue}} </p>
      <hr />
      <!-- 3) Repeat 2) but only output the entered value if the ENTER key was pressed -->
      <input type="text" v-on:keydown.enter="updateInputBoxText($event,secondInputBoxTextValue)"/>
      <p>OUTPUT {{secondInputBoxTextValue}}</p>
    </section>
  </body>
</html>`

尝试在线/在 StackOverflow 上/使用 ChatGPT - 希望能够使用方法中参数的值找到数据属性,更新

value as follows:const app = Vue.createApp({
    data(){
        return {
            firstInputBoxTextValue: "",
            secondInputBoxTextValue: ""
        };
    },
    methods: {
        showAlert(){
            alert("Button has been clicked..!");
        },
        updateInputBoxText(event,inputBoxTextIdentifier)
        {
            this[[inputBoxTextIdentifier]] = event.target.value;
        }
    }
});
javascript vue.js methods this dry
1个回答
0
投票

我以前从未在vue或js文件中见过[[]],它不是JavaScript的标准语法,正确的方法如下

<input type="text" v-on:keydown="updateInputBoxText($event,'firstInputBoxTextValue')"/>
...
updateInputBoxText(event, inputBoxTextIdentifier) {
  this[inputBoxTextIdentifier] = event.target.value;
}

© www.soinside.com 2019 - 2024. All rights reserved.