LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js インスタンス生成後に実行したいメソッド

Last updated at Posted at 2021-01-23

目的

開発中にページ読み込み時に実行したいメソッドがあった。 最初、window:onload を使ってみたがうまくいかなかった。

うまくいかない例

以下のコードではページ読み込み時にメソッドは実行されているのだが、コンソールで確認したところtitle に値が入っていなかった。


  <div id="app">
    <h1>{{ title }}</h1>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    title: ''
  },
  method: {
    window:onload = function() {
    this.title = 'Welcome to my page!'
    }
  }
})

解決策

method ではなくcreatedを使う

サンプルコード

  <div id="app">
    <h1>{{ title }}</h1>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    title: ''
  },
  created: function() {
    this.title = 'Welcome to my page!'
  }
})

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0