LoginSignup
0
0

More than 1 year has passed since last update.

petite-vueを使ってみる

Last updated at Posted at 2021-09-08
1 / 6

petite-vueとは?

  • petite-vue
  • Vueと同じテンプレート構文が使用できる
  • サーバーフレームワークによってレンダリングされた既存のHTMLページに少量のインタラクションを「振りかける」ために最適化されているらしい

とりえあず動かしてみる

githubのサンプル

  • petite-vueで操作するには、操作したいタグにv-scopeを付与する
  • v-scopeには操作する変数や関数をオブジェクトで指定する

スクリプトを分離してみる

  <div v-scope>
    {{count}}
    <button @click="increment">inc</button>
  </div>
  <script type="module">
    import { createApp } from 'https://unpkg.com/petite-vue?module'

    createApp({
      count: 0,
      increment() {
        this.count++;
      }
    }).mount()
  </script>
  • createAppにpetite-vueから操作する変数や関数をオブジェクトで渡す
  • mount()した値はルートスコープに指定され、v-scopeで指定しなくても関数や変数を使用できる

ファイルを分割してみる

今回はwebpackからpetite-vueを使ってみる。
webpackの設定については省略。

$ npm i petite-vue
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>hoge</title>
</head>
<body>
  <div v-scope>
    {{count}}
    <button @click="increment">inc</button>
  </div>
  <script src="main.js"></script>
</body>
</html>
main.js
import { createApp } from 'petite-vue'

createApp({
  count: 0,
  increment() {
    this.count++;
  }
}).mount()

railsで使ってみる

今回はwebpackerを使用するものとする。

petite-vueを追加する

$ npm i petite-vue
app/javascript/packs/count.js
import {createApp} from 'petite-vue';

createApp({
  count: 0,
  increment() {
    this.count++;
  }
}).mount();
app/views/counts/index.html.erb
<div v-scope>
  {{count}}
  <button @click="increment">inc</button>

  <%= javascript_pack_tag 'count' %>
</div>

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