computedとmethods
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>computedとmethodsの利点</title>
</head>
<body>
<div id="app">
<p>原価: {{ cost }}</p>
<p>利益: {{ profit }}</p>
<p>売価 (computed): {{ sellingPriceComputed }}</p>
<p>売価 (methods): {{ sellingPriceMethod() }}</p>
<button @click="increaseCost">原価を増やす</button>
</div>
<!-- CDN -->
<script src="CDN用URL"></script>
<script src="./main.js"></script>
</body>
</html>
// Vueアプリケーションの作成
Vue.createApp({
data() {
return {
cost: 100,
profit: 50,
};
},
computed: {
// computedプロパティ
sellingPriceComputed() {
return this.cost + this.profit;
},
},
methods: {
// methods関数
increaseCost() {
this.cost += 10;
},
sellingPriceMethod() {
return this.cost + this.profit;
},
},
}).mount("#app");
出力結果
原価: {{ cost }}
利益: {{ profit }}
売価 (computed): {{ sellingPriceComputed }}
売価 (methods): {{ sellingPriceMethod() }}