LoginSignup
0
0

More than 3 years have passed since last update.

Vueはルートの要素に1度だけmountするんだってさ

Posted at

コンポーネント?まぁ使わなくてもいけるでしょ

めんどくさがりやさんのぼくはVue.jsを使おうとしたにも関わらず、
公式のドキュメントを読まないおバカさんでした。

「だってなんか英語を翻訳したみたいな言葉で読みづらいんだモーン」

やがて、こんなことをしたくなってしまうのでした。



  • ページにViewModel(Vueインスタンス)をmountしたい
  • ページの一部分に別のViewModel(Vueインスタンス)をmountしたい

※イメージ

<div id="app">
  <q-btn @click="greet">greet</q-btn>
    <div id="app2">
    <q-btn @click="greet2">greet2</q-btn>
  </div>
</div>
<script>
    var app = new Vue({
    methods:{
      greet(){
        alert("hello app!")
      }
    }
  }).$mount("#app")
  var app2 = new Vue({
    methods:{
      greet2(){
        alert("hello app2!")
      }
    }
  }).$mount("#app2")
</script>

「なんとなくこうすりゃいいカンジあるな・・・」

とりあえずmountしてみてプロパティみてみる

<div id="app">
  {{msg}}
  <q-btn @click="greet">greet</q-btn>
    <div id="app2">
    {{msg}}
    <q-btn @click="greet2">greet2</q-btn>
  </div>
</div>
<script>
  var app = new Vue({
    data(){
      return{
        msg: "おはよう" // 表示される
      }
    },  
    methods:{
      greet(){
        alert("hello app!")
      }
    }
  }).$mount("#app")
  var app2 = new Vue({
    data(){
      return{
        msg: "こんちは" // 表示される
      }
    },
    methods:{
      greet2(){
        alert("hello app2!")
      }
    }
  }).$mount("#app2")
</script>

プロパティはバインドできている!!
おらおらおら~~~~~リファレンスなんて必要ないぜ~~~

メソッドも使えるでしょ?

<div id="app">
  {{msg}}
  <q-btn @click="greet">greet</q-btn>
    <div id="app2">
    {{msg}}
    <q-btn @click="greet2">greet2</q-btn>
  </div>
</div>
<script>
  var app = new Vue({
    data(){
      return{
        msg: "おはよう" // 表示される
      }
    },  
    methods:{
      greet(){
        alert("hello app!") // アラートがちゃんとでる
      }
    }
  }).$mount("#app")
  var app2 = new Vue({
    data(){
      return{
        msg: "こんちは" // 表示される
      }
    },
    methods:{
      greet2(){
        alert("hello app2!") // アラートがでない
      }
    }
  }).$mount("#app2")
</script>

「あっ・・・」

ゼウス「vueはルートの要素に1度だけmount。アプリつくってくときはほとんどコンポーネントになるよ。」

感想

リファレンス読もうっと。
https://jp.vuejs.org/v2/guide/

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