Vue / Nuxt - 在渲染整个视图后运行代码?

时间:2017-09-23 23:25:43

标签: vue.js vuejs2 nuxt.js

我希望在渲染完整个视图之后创建一些函数/ mounted

export default {
  mounted: function () {
    this.example = function() {
      return 'example'
    },
    function() {
      console.log('mounted') // does not work
    }
  },
  created () {
    console.log(this.example()) // error
  },
  methods: {
    submitMessage() {
      console.log(this.example()) // example
    }
  }
}

为什么我在created()处收到错误?

TypeError: this.example is not a function
    at VueComponent.created (index.vue:119)
    at callHook (vue.runtime.esm.js:2661)
    at VueComponent.Vue._init (vue.runtime.esm.js:4222)
    at VueComponent (vue.runtime.esm.js:4392)
    at createComponentInstanceForVnode (vue.runtime.esm.js:3674)
    at init (vue.runtime.esm.js:3491)
    at createComponent (vue.runtime.esm.js:5143)
    at createElm (vue.runtime.esm.js:5086)
    at VueComponent.patch [as __patch__] (vue.runtime.esm.js:5602)
    at VueComponent.Vue._update (vue.runtime.esm.js:2420)

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

created挂钩之前,mounted挂钩被称为。当created()函数运行时,this.example尚未声明。

宣布后,您可以致电this.created()

请参阅lifecycle diagram