Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

javascript - 如何使用此和(多个)动态括号符号更改vue数据变量(How to change a vue data variable using this and (multiple) dynamic bracket notations)

I am trying to achieve the following:(我正在努力实现以下目标:)

  1. I start of with ap element that contains the data variable "reportText.Scope_1_T_1", this variable contains the string: "Text to change";(我从包含数据变量“ reportText.Scope_1_T_1”的ap元素开始,此变量包含字符串:“ Text to change”;)
  2. On creation of this component, created() gets called and it fires off a call to the method createObject.(创建此组件时,将调用created()并触发对createObject方法的调用。) The method createObject requires multiple arguments, but the only relevant argument is the second one, which includes the location of the data variable I want to change (in this case: "reportText.Scope_1_T_1");(方法createObject需要多个参数,但唯一相关的参数是第二个参数,其中包括我要更改的数据变量的位置(在本例中为“ reportText.Scope_1_T_1”);)
  3. The method createObject splits this argument/location based on the dots and returns an array.(方法createObject根据点将参数/位置拆分,并返回一个数组。) So the string "reportText.Scope_1_T_1" returns the array ["reportText", "Scope_1_T_1"];(因此,字符串“ reportText.Scope_1_T_1”返回数组[“ reportText”,“ Scope_1_T_1”];)
  4. Following that this array gets looped through and combined with the context (=this).(之后,此数组将遍历并与上下文(= this)组合。) First loop results in context = this["reportText"], second loop returns in context = this["reportText"]["Scope_1_T_1"].(第一个循环返回上下文= this [“ reportText”],第二个循环返回上下文= this [“ reportText”] [“ Scope_1_T_1”]。)
  5. After this I assign a new String to context (context = reply.fields)(之后,我为上下文分配一个新的字符串(context = reply.fields))

My expectation was that this code would result in a change of the data variable this.reportText.Scope_1_T_1, but unfortunately nothing happens to this variable.(我的期望是,此代码将导致数据变量this.reportText.Scope_1_T_1发生更改,但不幸的是,此变量没有任何反应。)

I have tried playing around with dot notation and bracket notation, but nothing really worked.(我曾尝试使用点符号和方括号符号,但实际上没有任何作用。)

For example if I try to change the code in my createObject method to this:(例如,如果我尝试将我的createObject方法中的代码更改为此:)
  • this.reportText.Scope_1_T_1 = "New String";(this.reportText.Scope_1_T_1 =“新字符串”;) or(要么)
  • this["reportText"]["Scope_1_T_1"] = "New String";(this [“ reportText”] [“ Scope_1_T_1”] =“新字符串”;)

It suddenly does work?(突然起作用了吗?)

I don't understand why.(我不明白为什么。) I even tried to see if I somehow make a copy of 'this' so it doesn't reference the same object, but as far as I see it doesn't make a copy.(我什至试图查看是否以某种方式复制了“ this”,因此它没有引用相同的对象,但据我所知,它没有复制。) It does seems to be a reference problem, because it somehow points to a different location when I use my dynamic brackets.(这似乎确实是一个参考问题,因为当我使用动态括号时,它以某种方式指向了另一个位置。)

Here is my relevant code(if you need more, please let me know):(这是我的相关代码(如果您需要更多代码,请告诉我):)

<template>
  <p>{{ reportText.Scope_1_T_1 }}</p>
</template>

<script>
export default {
  data: function() {
    return {
      reportText: {
        Scope_1_T_1: 'Text to change'
      }
    }
  },
  created() {
    this.$store.getters.getAppPromise.then(app => {
      this.createObject(app, 'reportText.Scope_1_T_1', 'String', '=irrelevantExpression');
    })
  },
  methods: {
    createObject(app, location, type, expression) {
      if (type === 'String') {
        app.createGenericOjbect(
          {
            fields: {
              qStringExpression: expression
            }
          },
          reply => {
            let context = this;
            location = location.split('.');

            location.forEach(item => {
              context = context[item];
            });

            context = reply.fields;
          }
        )
      }
    }
  }
}
</script>

I would greatly appreciate it if anyone could help me figure out what the difference is between using my dynamically created context and a static context (like this: this["reportText"]["Scope_1_T_1"]).(如果有人能帮助我弄清楚使用动态创建的上下文和静态上下文(例如:this [“ reportText”] [“ Scope_1_T_1”])之间的区别,我将不胜感激。)

I think that's the key in solving this problem.(我认为这是解决此问题的关键。)

My code is based on this stackoverflow question: Javascript Square Bracket Notation Multiple Dynamic Properties(我的代码基于以下stackoverflow问题: Javascript方括号表示法多个动态属性)

  ask by CvP translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's just the final step that won't work.(这只是最后一步,将无法正常工作。)

Assigning a new value to context at the end will just update that local variable, not the property of the object.(最后,为context分配一个新值只会更新该局部变量,而不是对象的属性。)

Instead what you need to do is grab a reference to the relevant object and then update the property.(相反,您需要做的是获取对相关对象的引用,然后更新属性。)

To grab the object you need to drop the final section from the location path.(要抓住对象,您需要从location路径中删除最后一部分。) That final section is then the property name that needs to be updated:(然后,最后一部分是需要更新的属性名称:)
let context = this;
const path = location.split('.');
const property = path.pop()

path.forEach(item => {
  context = context[item];
});

context[property] = reply.fields;

The syntax used for property access hides some asymmetry in how the parts of the path are interpreted.(用于属性访问的语法在解释路径的各个部分时隐藏了一些不对称性。)

Consider this example:(考虑以下示例:)

const a = b.c.d.e

What happens is:(发生的是:)

  1. Start with b .(从b开始。)
  2. Grab the value in property c .(获取属性c的值。)
  3. Grab the value in property d .(获取属性d的值。)
  4. Grab the value in property e .(获取属性e的值。)
  5. Assign that value to a .(分配一个值到a 。)

All nice and symmetric, c , d and e all seems to work the same way.(cde都很好且对称,似乎都以相同的方式工作。)

Now consider flipping that example:(现在考虑翻转该示例:)

b.c.d.e = a

This is very different.(这是非常不同的。)

  1. Start with b .(从b开始。)
  2. Grab the value in property c .(获取属性c的值。)
  3. Grab the value in property d .(获取属性d的值。)
  4. Assign a to the property e .(将a分配给属性e 。)

In this scenario the c and d properties are still just read operations but the e is handled totally differently.(在这种情况下, cd属性仍然只是读取操作,但是e的处理方式完全不同。)

That final part is a write operation instead.(最后一部分是写操作。)

The key thing to appreciate here is that the final part of a 'path' like this is special when you want to set the value.(这里要领会的关键是,当您要设置值时,像这样的“路径”的最后一部分是特殊的。)

Normally this hides behind the syntax but when you want to break it down like in your example you need to be conscious of what is actually going on.(通常,这隐藏在语法的后面,但是当您想像示例中那样分解它时,您需要意识到实际情况。)

Whether you use .(是否使用.)

or [] notation makes no difference to this behaviour, though to access properties dynamically you have to use [] .(或[]表示法对这种行为没有影响,尽管要动态访问属性,您必须使用[] 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...