【问题标题】:In Vue components, mounted: {this.init()}, raises an error : Unexpected token, expected {在 Vue 组件中,挂载:{this.init()},引发错误:Unexpected token, expected {
【发布时间】:2026-02-03 14:55:01
【问题描述】:

结合Vue和echarts的时候,我在src/components/Chart.vue中写了这个:

<script>
export default {
  name: 'Charts',
  data () {
    return {
      chart: ''
    }
  },
  computed: {
    style () {
      return {
        height: this.height,
        width: this.width
      }
    }
  },
  mounted: {this.init()},
  methods: {
    init () {
      this.chart = this.$echarts.init(document.getElementById(this.id))
      this.charts.setOption(this.option)
    }
  }
}
</script>

当运行npm run dev 时,它提出了这个:

 ERROR  Failed to compile with 1 errors                                                   22:51:02

 error  in ./src/components/Chart.vue

Syntax Error: this is a reserved word (57:12)

  55 |     }
  56 |   },
> 57 |   mounted: {this.init()},
     |             ^
  58 |   methods: {
  59 |     init () {
  60 |       this.chart = this.$echarts.init(document.getElementById(this.id))



 @ ./src/components/Chart.vue 4:0-105 5:0-118
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

我用谷歌搜索了很多,但没有找到答案。如果有人能启发我,我将不胜感激。

【问题讨论】:

  • 这只是无效的语法。你想在那里发生什么?您所拥有的是使用对象初始化程序(“对象文字”)定义属性,并且函数调用在对象初始化程序的主体中本身是无效的。

标签: javascript vue.js vue-cli echarts


【解决方案1】:

mounted 应该引用一个函数字面量,所以试试这个

mounted: function() { this.init() }

【讨论】:

    【解决方案2】:

    和你对数据做的一样,mounted应该是一个函数:

    mounted () {
        this.init()
    },
    

    【讨论】: