从方法中只调用一种方法 [英] Call only one method from methods

查看:28
本文介绍了从方法中只调用一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本例中,我通过以下方法更改name":

new Vue({el: '#锻炼',数据: {name: '彼得',},方法: {随机:函数(){返回 Math.random();},更改名称:函数(事件){this.name = event.target.value;}}})

<script src="https://unpkg.com/vue/dist/vue.js"></script><div id="锻炼"><p>VueJS 非常酷 - {{ name }}</p><p>{{random()}}</p><div><input v-on:input="changeName" type="text">

但是每次我调用方法 changeName 时,另一个方法(random)也会被调用.

为什么?

解决方案

来自 计算属性 - 计算缓存 vs 方法:

<块引用>

相比之下,只要发生重新渲染,方法调用将始终运行该函数.

什么时候重新渲染?当数据发生变化时.

在您的示例中,每当您输入 <input>(因为它调用 changeName)时,数据(即 name)都会发生变化.

查看生命周期图 - 更多具体来说,Mounted"红球:

查看下面的演示,您会看到那些生命周期事件正在发生(以及它们之间的重新渲染):

new Vue({el: '#锻炼',数据: {name: '彼得',},更新前(){console.log('beforeUpdate 执行');},更新() {console.log('更新执行');},方法: {随机:函数(){返回 Math.random();},更改名称:函数(事件){this.name = event.target.value;}}})

<script src="https://unpkg.com/vue/dist/vue.min.js"></脚本><div id="锻炼"><p>VueJS 非常酷 - {{ name }}</p><p>{{random()}}</p><div><input v-on:input="changeName" type="text">

On this example, I change the "name" via the method:

new Vue({
  el: '#exercise',
  data: {
    name: 'Petr',
  },
  methods: {
    random: function() {
      return Math.random();
    },
    changeName: function(event) {
      this.name = event.target.value;
    }
  }
})

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="exercise">
  <p>VueJS is pretty cool - {{ name }}</p>
  <p>{{ random() }}</p>
  <div>
    <input v-on:input="changeName" type="text">
  </div>
</div>

But each time I call the method changeName the other method (random) also is called.

Why?

解决方案

From Computed Properties - Computed Caching vs Methods:

In comparison, a method invocation will always run the function whenever a re-render happens.

And when does a re-render happen? When data changes.

And in your example data (i.e. name) changes whenever you type into the <input> (because it calls changeName).

Check the lifecycle diagram - more specifically, the "Mounted" red ball:

Check the demo below, so you see those lifecycle events are happening (and thus the re-rendering between them):

new Vue({
  el: '#exercise',
  data: {
    name: 'Petr',
  },
  beforeUpdate() {
    console.log('beforeUpdate executed');
  },
  updated() {
    console.log('updated executed');
  },
  methods: {
    random: function() {
      return Math.random();
    },
    changeName: function(event) {
      this.name = event.target.value;
    }
  }
})

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<div id="exercise">
  <p>VueJS is pretty cool - {{ name }}</p>
  <p>{{ random() }}</p>
  <div>
    <input v-on:input="changeName" type="text">
  </div>
</div>

这篇关于从方法中只调用一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆