0
1

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.

vue.js 備忘録 v2からv3への変更点<基本のき>

Last updated at Posted at 2021-05-26

・Vue2と3の違いについて

vue2のバージョン
→Option APIとしてバラバラに書いていた

export default {
  data() {},
  methods: {},
  computed: {},
  mounted() {},
};

vue3のバージョン
→Composition APIとして一つにまとめた記述方法をすることになる
→setup()はmountedなどの他のライフサイクルよりも早く行われる

export default {
  setup() {
    // data
    // methods
    // computed
    // Lifecycle hooks
  },
};

2とは違い、3ではsetup関数内に全てを記述してしまうのだ

・気をつけなければいけない点
→reactiveかreactiveではないか

<template>
  <div class="home">
    <h1>Home</h1>

    <p>My name is {{ name }} and my age is {{ age }}</p>
  </div>
</template>

<script>
export default {
  name: "Home",
  setup() {
    let name = "hogehoge";
    let age = 30;

    return { age, name };
  },
  data() {
    return {
      age: 48,
    };
  },
};
</script>

上のソースコードではマスタッシュ構文ないにあるageはどちらを表示するであろうか
→答えは48
→なぜなら30の方のageはreactiveな値ではないからだ
→そのため、reactiveな値である48が画面に描画されてしまう
→そうならないためにも、data()とsetup()で同一の変数を置くのは控えた方がよろしいだろう
→ではsetupでおいた変数をreactiveにするにはどうすればいいのだろうか
→「ref」を使用する

<template>
  <div class="home">
    <h1>Home</h1>

    <p ref="p">My name is {{ name }} and my age is {{ age }}</p>

    <button @click="handleClick">plese click</button>
  </div>
</template>

<script>
import { ref } from "vue";

export default {
  name: "Home",
  setup() {
    const p = ref(null);
    // refという物を使用すると、reactiveになる
    let name = ref("mario");
    let age = ref(30);

    const handleClick = () => {
      // refをしている値を変えたい時は変数.valueを使用する
      name.value = "hogehoge";
    };

    return { age, name, handleClick, p };
  },
};
</script>

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?