首页 > 解决方案 > 在 Vue 组件中,挂载:{this.init()},引发错误:Unexpected token, expected {

问题描述

在结合 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

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

标签: javascriptvue.jsvue-cliecharts

解决方案


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

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


推荐阅读