2

I have this code here:

<template>
    <div>
        <button @click="changeData(text)">click me !</button>
        <p>{{ text }}</p>
    </div>
</template>

<script>
    export default {
        data () {
            return {
                text: 'lorem'
            }
        },
        methods: {
            changeData(param){
                this.param = 'lorem 1'
            }
        }
    }
</script>

I wanna click button then change "text" variable by param in function changeData

1
  • changeData("text") => this["text"] => strong. But: changeData("object.name") => this["object.name"] => wrong Commented Mar 6, 2020 at 6:23

2 Answers 2

4

If you want to change the value text variable then value that you are passing 'parm' as a value in the function should be allocated to text(local variable). Example:

   <template>
        <div>
            <button @click="changeData('NewValue')">click me !</button>
            <p>{{ text }}</p>
        </div>
    </template>

    <script>
        export default {
            data () {
                return {
                    text: 'lorem'
                }
            },
            methods: {
                changeData(param){
                    this.text=param
                }
            }
        }
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to change the text attribute, then you have to change the text attribute, not the param attribute.

You seem to think that since you're calling changeData(text) that param's value is text (correct) and this.param is replaced by this.text (wrong).

What you're doing currently is changing the param attribute to have the value 'lorem 1'.

If you want the changeData function to replace the value of text, then you have to change the code inside to this.text = <new value>, replacing <new value> with either a string literal or a parameter of your function.

If you want the changeData function to replace the value of an indicated parameter to 'lorem 1', then you need to use this[param] = 'lorem 1' instead.

1 Comment

I tried the way you said earlier. but in a case like this it won't be true anymore: changeData("object.name") => this["object.name"] => wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.