Vue.js v-cloakのサンプルコード

Vue.js v-cloakのサンプルコード

v-cloakを利用して、バインディングされる前に mastache構文( {{hoge}} ) が表示されないようにするサンプルコード

環境

  • OS  Windos10
  • エディタ VScode

サンプルコード

下記のソースコードをindex.htmlとして作成して保存します。

vue.jsは下記の開発バージョンのものを利用してます <script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
.style1 {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 120px;
}        
h3 {
    margin: 40px 0 0;
    color: #41B883;
}
h4 {
    margin: 40px 0 0;
    color: #35495E;
}
.button {
    display: block;
    position: relative;
    margin: 0 auto;
    width: 140pt;
    border: solid 1px silver;
    border-radius: 0.5rem 0.5rem;
    padding: 0.5rem 1.5rem;
    margin-top: 1rem;
    text-decoration: none;
}
/*[v-cloak] {display: none;} によりバインディングされるまでは非表示となる*/
[v-cloak] {
  display: none;
}
</style>
<body>
 
<div id="app" class="style1">
    <h3>v-cloakサンプル 3秒後にバインディング開始</h3>
    <h4>v-cloakあり</h4>
    <p id="test1" v-cloak>{{name}}</p>
    <h4>v-cloakなし</h4>
    <p id="test2">{{name}}</p>
</div>
 
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
setTimeout(function() {
  new Vue({
    el: "#test1",
    data: {
      name: "test1"
    }
  });
  new Vue({
    el: "#test2",
    data: {
      name: "test2"
    }
  });
}, 3000);
</script>
</body>
</html>

保存したファイルをブラウザで開いて確認 。

js部の setTimeout で3秒後にバインディングが開始される。
v-cloakなしの方は{{name}}が表示される

3秒後。v-cloakありの方も、なしも方もバインディングされる