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
119 views
in Technique[技术] by (71.8m points)

javascript - VueJS is updating another element on an event

I have just started learning VueJS and while writing some code I noticed that another HTML element was getting updated on event fire.

app.js

const app = Vue.createApp({
    data(){
        return {
            name: "Name",
            age: 21,
            url: "",
            input_data: "",
        }   
    },
    methods: {
        getRandom(){
            return Math.random();
        },
        setText(event){
            this.input_data = event.target.value;
        },
    }
}).mount('#assignment');

index.html

<section id="assignment">
      <h2>{{name}}</h2>

      <input type="text" v-on:input="setText($event)" />
      <p>{{input_data}}</p>

      <p>{{age}}</p>

      <p>{{age+5}}</p>

      <p>Favorite Number: {{getRandom()}}</p>
      <div>
        <img v-bind:src="url" />
      </div>

</section>

Whenever I enter text in the input field it does update

tag with {{input_data}} but it also updates the Favorite Number section which is not as expected. Does anyone know why is this happening?

I'm using latest version of Vue(3.0.5) from CDN

Thanks,

-Atharva


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

1 Reply

0 votes
by (71.8m points)

Alireza already provided a workaround/solution but here comes the explaination.

When your Vue app loads it reads the template you have provided and replaces all the {{tags}} with the values. To get the value of {{getRandom()}} it calls the method getRandom().

Whenever any of the underlying values changes Vue will repeat this process. Now you see the new values on your screen. This is what they mean with Vue's reactivity.

Now because you changed input_data the template gets reevaluated, which again calls the getRandom() function. This is why that value 'unexpectedly' changed when you inputted some text.


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

...