4. Conditional Rendering
クラス https://www.vuemastery.com/courses/intro-to-vue-3/conditional-rendering-vue3
VS Codeから該当フォルダを選択して、開きます。その後に、配下のgit部分をクリックして、ブランチをL4-startへ入れ替えてください。
ブランチ切り替え方法
今日のポイントは条件による、バインドです。
入っているデータオブジェクトの値により、判定して、バインドされる部分などの調整ができます。
index.html
<p>In Stock</p>
<p>Out of Stock</p>
単純な条件の場合は下記のように実装します。
main.js
const app = Vue.createApp({
data() {
return {
product: 'Socks',
image: './assets/images/socks_blue.jpg',
inStock: true // new data property //
}
}
})
index.html
<p v-if="inStock">In Stock</p>
<p v-else>Out of Stock</p>
条件を複数にしたい場合は、下記のようになります。
main.js
const app = Vue.createApp({
data() {
return {
product: 'Socks',
image: './assets/images/socks_blue.jpg',
inventory: 100
}
}
})
index.html
<p v-if="inventory > 10">In Stock</p>
<p v-else-if="inventory <= 10 && inventory > 0">Almost sold out!</p>
<p v-else>Out of Stock</p>
今回の課題はonSaleをBooleanデータオブジェクトとして、追加してOn Saleタグを条件により、レンダリングして見てください。
課題確認
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vue Mastery</title>
<!-- Import Styles -->
<link rel="stylesheet" href="./assets/styles.css" />
<!-- Import Vue.js -->
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<div class="nav-bar"></div>
<div class="product-display">
<div class="product-container">
<div class="product-image">
<img v-bind:src="image">
</div>
<div class="product-info">
<h1>{{ product }}</h1>
<!-- solution -->
<h2>anchor : <a :href="anchorUrl" target="_blank">{{ anchor }}</a></h2>
</div>
</div>
</div>
</div>
<!-- Import App -->
<script src="./main.js"></script>
<!-- Mount App -->
<script>
const mountedApp = app.mount('#app')
</script>
</body>
</html>
main.js
const app = Vue.createApp({
data() {
return {
product: 'Socks',
image: './assets/images/socks_green.jpg',
// solution
anchor: 'phjg81',
anchorUrl: 'https://qiita.com/phjg81'
}
}
})