为什么在computed()中使用时无法识别Vue函数?

时间:2018-02-27 14:19:04

标签: javascript vue.js

以下代码(安装组件时在字符串模板中使用Vue method)起作用::

new Vue({
  el: "#app",
  methods: {
    perc: w => w / 100
  },
  mounted() {
    console.log(`hello ${this.perc(20)}`)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>

下面的内容=以上展开以在this.perc()变量中使用computed,失败并显示TypeError: this.perc is not a function

new Vue({
  el: "#app",
  methods: {
    perc: w => w / 100
  },
  computed: {
    data: {
      y: `hello ${this.perc(20)}`
    }
  },
  mounted() {
    console.log(this.data)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>

为什么计算变量中没有this.perc()

1 个答案:

答案 0 :(得分:2)

它必须是computed property中的函数。

&#13;
&#13;
new Vue({
  el: "#app",
  methods: {
    perc: (w) => w / 100
  },
  computed: {
    data () {
      return `hello ${this.perc(20)}`
    }
  },
  mounted() {
    console.log(this.data)
  }
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;