LoginSignup
0
0

More than 3 years have passed since last update.

【Vue.js】Vueコンポーネントの中ではdataは関数である必要がある。

Posted at

Vue.jsのコンポーネントについて復習しています。

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.8/dist/vue.js"></script>

<div id="app">
 <my-component></my-component>
</div>
Vue.component('my-component', {
  data: {
   number: 12
  },
  template: '<p>いいね({{number}})</p>'
})

new Vue({
 el: "#app",
})

これだとtemplateの中に記述されているnumberの12が表示されていない。
スクリーンショット 2021-04-17 14.01.44.png

本当は、()のなかに12と表示させたい。

コンポーネントの中ではdataは関数にする必要がある。

コンポーネントの中ではdataは関数にする必要があります。
だから、記述を少しだけ変更します。

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.8/dist/vue.js"></script>

<div id="app">
 <my-component></my-component>
</div>
Vue.component('my-component', {
    data: function(){
    return {
     number: 12
    }
  },
  template: '<p>いいね({{number}})</p>'
})

new Vue({
    el: "#app",
})

dataを関数にして、returnで返したいオブジェクトを記述します。
ここでは以下のように記述を変更しました。

    data: function(){
    return {
     number: 12
    }

これで()の中に12という文字が表示されるようになりました。
スクリーンショット 2021-04-17 14.06.27.png

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