javascript - vue.js 数据中的方法和方法中的方法的区别

标签 javascript vue.js

我想知道在数据中声明的方法与在方法中声明的方法有什么区别?

var app = new Vue({
  el: "#vue-app",
  data: {
    name: function() {
      console.log("Alex");
    }
  },
  methods: {
    name: function() {
      console.log("Alex");
    }
  }
});

最佳答案

tl;dr 如果您的内部只有一个 console.log("Alex"),它们的工作原理是一样的。但是如果你在它们里面有一个this,它们就会有很大的不同。


首先,Vue data 对象应该是没有方法的纯 JavaScript 对象。来自 the API docs :

The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it “reactive”. The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

因此,即使它有效,我也会在 methods 中声明它们以遵循 POLA .

一个关键的区别:

但是,更重要的是,有一个关键因素:方法绑定(bind)到 Vue 实例。这意味着 this 内部方法 总是指向当前的 Vue 实例。

new Vue({
  el: '#app',
  data: {
    nameData: function() {
      console.log("nameData", this.otherMethod()) // doesn't work
    },
  },
  methods: {
    nameMethod: function() {
      console.log("nameMethod", this.otherMethod()); // works
    },
    otherMethod() {
      return "I am other method";
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <button @click="nameData">invoke nameData</button><br>
  <button @click="nameMethod">invoke nameMethod</button>
</div>

又一个例子:

new Vue({
  el: '#app',
  data: {
    id: 3,
    ids: [1,2,3,4],
    equalsIdData: function(i) {
      return this.id === i;
    },
  },
  methods: {
    equalsIdMethod: function(i) {
      return this.id === i;
    },
    yetAnotherMethod: function() {
      console.log('equalsIdMethod:', this.ids.filter(this.equalsIdMethod)); // filters correctly
      console.log('equalsIdData:',   this.ids.filter(this.equalsIdData)); // filters incorrectly
    },
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <button @click="yetAnotherMethod">invoke yetAnotherMethod</button>
</div>

关于javascript - vue.js 数据中的方法和方法中的方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804235/

相关文章:

javascript - 网格中的最后一列需要自定义标题

javascript - 按照 HTML 语言更改事件语言图标+名称

vue.js - 如何在 VueJS 的 <router-link> 中提供动态 URL?

laravel - Vue 多选 laravel 提交表单

navigation - Vue Router 多个独立的router-view导航

javascript - 使用 JSON 的 Highcharts - 图表不显示 mysql 数据

javascript - jquery 输入验证正则表达式

vue.js - 计算观察者方法调用时,vue jest spyOn 不起作用

javascript - 使用 JS 禁用打印

vue.js - v-model 触发更改事件两次