LoginSignup
1
1

More than 3 years have passed since last update.

VueコンポーネントをjQueryで動的にマウントする

Posted at

VueコンポーネントをjQueryで動的にマウント

Kintoneのプラグイン開発でVueコンポーネントを動的にマウントしなければいけない場面があり、情報がなかなか集まらず苦戦したのでメモする。

0. webpackを使用している場合はaliasを追加

最後この情報を得ることができず解決まで時間がかかったので、この設定が一番重要かもしれない。

webpack.config.js
module.exports = {
    resolve: {
        alias: {
            "vue$": "vue/dist/vue.esm.js"
        }
    }
}

1. Vue.extendを使う

まず純粋にVue.componentでコンポーネントを作るのではなく、Vue.extendを使いVueのサブクラスを作成する。(参照:API - Vue-extend)

const Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  }
})

2. jQueryでDOMを作成

次に作成したサブクラスのマウント先になるDOMをjQueryで作成し、任意の場所に追加する。

const app = $("<div id='app'></div>");
$("body").append(app);

3. Vueサブクラスをマウントする

const component = new Profile();
component.$mount("#app"); // 2で作成したDOMを指定
1
1
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
1
1