4
0

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】意図しないタイミングでcreatedが発火していた。

Last updated at Posted at 2021-03-11

タイトルの件で躓きましたので、再現方法と解決法を記載します。

問題のあるコード

ボタンを押した時に、コンポーネントとは関係のないdivの表示非表示を切り替えているだけなのですが、実際にこのコードを動かすとコンポーネント内のcreatedが発火してしまいます。

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>vue-component-test</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="show = !show">show toggle</button>
        <div v-if="show">div1</div>
        <div>
            <my-component></my-component>
        </div>
        <div v-if="show">div2</div>
    </div>
</body>
<script>
    Vue.component('my-component', {
        template: '<div>my component</div>',
        created() {
            console.log('created!');
        }
    })

    new Vue({
        el: '#app',
        data: { show: true }
    })
</script>
</html>

なぜなのか

componentの親divの前後のdivが同時に消えた際に、同一のDOMと認識されずに再描画されてしまっているのだと思います。
(内部のアルゴリズムまでは見られていないので有識者がいらっしゃったらご教示いただきたいです)

どうしたか

keyを与えてあげて、同一DOMだよっていうことをvueに教えてあげました

index.html
        <!-- 前略 -->
        <div :key="myComponent">
            <my-component></my-component>
        </div>
        <!-- 後略 -->

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?