5
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

さくっとVue3をWebブラウザで試したい時に使えるTips

Last updated at Posted at 2020-07-27

Vue3がRCになっていよいよリリース間近ですね。
環境構築不要でさくっとVue3の動き確認したいなーって時に使えるTipsを紹介します。

script要素を追加し、CDNからVue3のスクリプトを読み込む

適当なサイトを開き、以下コードをWebブラウザのdevtoolsのconsole上で実行してください。
srcにvue-nextのCDNのアドレスを設定したscript要素を作成し、body直下に追加しています。

document.body.appendChild(
  (() => {
    const s = document.createElement("script");
    s.src = "https://unpkg.com/vue@next";
    return s;
  })()
);
スクリーンショット 2020-07-25 5.34.19.png

これでvue-nextのCDNが読み込めたので、console上でVueが使えます。
あとはやりたい放題使えばOKです。

スクリーンショット 2020-07-25 8.32.41.png

動作確認コードの一例

参考までに、自分で動かしてみたコードを紹介します。

Vueコンポーネントの動作確認

DOMを追加して、そこにVue.createApp()でVueをマウントしコンポーネントを表示しています。templatesetup()内を調整すればほとんどの動作を確認できます。

// マウント用のDOMの追加
document.body.insertBefore((() => {
  const d = document.createElement("div");
  d.id = 'vue-app';
  return d;
})(), document.body.firstChild);

// DOM要素へのVueコンポーネントのマウント
const app = Vue.createApp({
  template: `<my-component />`
})
app.component('my-component', {
  template: `
    <h1>Hello Vue3</h1>
    <input type="text" v-model="message"/>
    <div>{{ upperCase }}</div>
  `,
  setup() {
    const message = Vue.ref('')
    const upperCase = Vue.computed(() => message.value.toUpperCase())
    return {
      message,
      upperCase
    }
  }
})
app.mount('#vue-app')

yahoo! JAPANで実行してみた例
Jul-25-2020 08-27-10.gif

リアクティブの動作確認

Vue3のComposition APIのリアクティブAPIの動作確認です。refでもreactiveでも同様にリアクティブに処理を再実行してますね。

const reactiveObj = Vue.reactive({ count: 1 });
const refObj = Vue.ref(1);
const sumVal = Vue.computed(() => reactiveObj.count + refObj.value);

console.log(sumVal.value); // 2

refObj.value = 3;
console.log(sumVal.value); // 4

reactiveObj.count = 10;
console.log(sumVal.value); // 13
スクリーンショット 2020-07-25 5.43.55.png

リアクティブの消失の動作確認

Vue Composition APIを使う上で注意が必要なリアクティブの消失について動作確認です。リアクティブな値から分割代入でプリミティブな値を取得すると、リアクティブを消失するのが良くわかると思います。

const reactiveObj = Vue.reactive({
  num: 1,
  str: "hoge",
  arr: [1, 2, 3],
  obj: { foo: "foo", bar: "bar" },
});

const { num, str, arr, obj } = reactiveObj;

console.log(Vue.isReactive(num)); // false
console.log(Vue.isReactive(str)); // false
console.log(Vue.isReactive(arr)); // true
console.log(Vue.isReactive(obj)); // true
スクリーンショット 2020-07-25 6.33.28.png

終わりに

とても簡単ですが「さくっとVue3をWebブラウザで試したいときに使えるTips」でした。
ちょっと動きを確認したいときとかに地味に便利なので使ってみてください〜。

5
9
1

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
5
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?