为什么 vue.js 计算得到未定义

Arc*_*hsx 1 javascript vue.js

我只是想使用 Vue 计算,但我得到了undefined(styleObj.width),而且似乎没有调用计算函数(没有记录“计算”)。当我更改数据而计算函数仍未被调用并且数据(styleObj.width)仍然是undefined.

代码很简单,我希望你知道我在说什么。

<!DOCTYPE html>
<html>
  <head>
    <script src="http://vuejs.org/js/vue.js"></script>
    <meta charset="utf-8" />
    <title>JS Bin</title>
    <style>
      #app {
        height: 100px;
        background: red;
      }
    </style>
  </head>
  <body>
    <div id="app" :style="styleObj"></div>

    <script>
      var vm = new Vue({
        el: '#app',
        data: {
          num: 100,
          styleObj: {
            width: this.calcWidth, // always be undefined even num has changed
          },
        },
        computed: {
          calcWidth() {
            console.log('computed') // never log 'computed' which means the
            // calcWidth not be called
            return this.num + 'px'
          },
        },
      })

      setTimeout(() => {
        vm.num = 200
      }, 2000)
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 为什么calcWidth永远不会调用该函数?我认为它会在开始时和 2 秒后被调用两次,但永远不会被调用。为什么?

  2. 为什么styleObj.width一直未定义?

ski*_*tle 5

有几个问题。

它目前的编写方式,thisinwidth:this.calcWidth不会指代正确的对象。它需要在一个函数内才能获得正确的范围。这很容易通过更改data为函数来解决。

下一个问题是计算属性在data函数中不可用。顺序大概是:

  1. 提供/注入
  2. 道具
  3. 数据
  4. 计算

列表下方的内容可以使用列表上方的内容,而不是相反。

相反,您可以使整个样式对象成为计算属性:

computed: {
  styleObj () {
    return {
      width: this.num + 'px'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者如果您更愿意保留calcWidth

computed: {
  styleObj () {
    return {
      width: this.calcWidth
    }
  }
}
Run Code Online (Sandbox Code Playgroud)