[Vuejs]-Vuejs class component fields undefined

0👍

For the best use change you code to this:

//...
@Component({
  template: `
    <div>
    <h1>{{ message }}</h1>
    <h1>{{ shrek }}</h1>
    </div>

  `
})
class App extends Vue {
  data(){
    return {
       shrek: 'test',
       message: 'Hello world!'
    };
  }
  created(){
    this.shrek = "This is my swamp!";
    console.log(this.shrek);
    this.print();
  }

  print(){
      console.log(this.shrek);
  } 
}

new Vue({
  el: '#app',
  render: h => h(App)
})
//...

On your link here

0👍

After having practiced using Vue for a few more weeks and researching various topics on the internet I have come to the conclusion (which should have been obvious to me at first) that the answer is to use components only for what components are good for. That is to say, if you have some logic that gets gnarly and you want to alleviate it with helper functions, those helper functions can be declared outside the class as regular functions and used within the component code. Another upside of this approach is that if multiple components would get use out of your helper function or initialization code, you can instead move it into a typescript or javascript module and import it into those components that need it.

データ初期化や普通の論理を実施するヘルパー関数をコンポーネント内に置くより別の標準なTypescriptやJavascript関数に置いた方が良さそうです。Vuejsのコンポーネント・クラスの良い点はview作りだけでviewと関係ない論理をコンポーネント以外に置くべきです。それにそうするとその論理を別のファイルに置いてモジュール形で複数のコンポーネントはその論理を使えるようになります。

Leave a comment