Vue.js computed(算出プロパティ)の使い方

Vueのcomputedの使い方の簡単なサンプルコードです。methodsとは違い実行結果がキャッシュされるのが特徴です。
環境
- OS CentOS 8.0.1905 (Core)
- node v12.13.1
- npm 6.13.2
- @vue/cli 4.1.1
- bootstrap-vue 2.1.0
Vue.js環境構築
vueappという名前でプロジェクトを作成
vue create vueapp
cd vueapp
## bootstrapインストール
npm i -S bootstrap-vue
bootstrapを使用するため、srcディレクトリ配下のmain.jsを下記のように編集
import Vue from 'vue'
import App from './App.vue'
import BootstrapVue from 'bootstrap-vue';
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(BootstrapVue);
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
computedの使い方
componentsディレクトリ配下のHelloWorld.vueを下記の通りに編集します。
<template>
<div class="hello container-fluid">
<div class="mx-auto col-md-6">
<b-button v-on:click="showTime()">{{text}}</b-button>
<div v-if="show">
<b-alert show>Computed(変化なし) <p v-text="timeComputed"></p></b-alert>
<b-alert variant="success" show>Method(変化する)<p v-text="timeMethod()"></p></b-alert>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
show: true,
text: "非表示"
}
},
props: {
msg: String
},
methods: {
timeMethod: function() {
return Date.now();
},
showTime(){
this.show=!this.show
if(this.show){
this.text="非表示"
}
else{
this.text="表示"
}
}
},
computed: {
timeComputed: function() {
return Date.now();
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
npm run serveで起動後に、ブラウザから http://プライベートIP:8080 にアクセスするとComputedにより、Date.nowにより取得した値が表示されます。
Computedの方は算出された値がキャッシュされ、methods算出された値はキャッシュされていないことが確認できます。

-
前の記事
Nuxt.js vue-go-topを使用して画像にエフェクトかける 2020.02.10
-
次の記事
Vue.js vue-particle-effect-buttonsを使ってアニメーションのかかったbuttonを実装する 2020.02.11
コメントを書く