Vue.jsの勉強中なのですが、methodsの動作についてよくわからないことがあり質問させてください。
以下のコードについてですが、切り替えボタンを押すと、listの表示がpriceの昇順/降順になります。
このとき、list表示と無関係の {{ methodsData() }} の部分が書き換わります。また、console.logで出力してみるとmethodsData()が2回呼ばれています。
なぜmethodsData()が呼ばれるのか教えて頂けましたら幸いです。
よろしくお願いいたします。
(環境:Windows10, Google Chrome v72.0.3626.96, vue@2.5.21)
html
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4<meta charset="utf-8"> 5<title>Vue.jsの勉強</title> 6</head> 7<body> 8<div id="app"> 9 10 <p>{{ computedData }}</p> 11 <p>{{ methodsData() }}</p> 12 13 <button v-on:click="order=!order">切り替え</button> 14 <ul> 15 <li v-for="item in limited" v-bind:key="item.id"> 16 {{ item.name }} {{ item.price }} 円 17 </li> 18 </ul> 19 20</div> 21 22<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script> 23<script src="main.js"></script> 24</body> 25</html>
javascript
1new Vue({ 2 el: '#app', 3 data: { 4 list: [ 5 { id: 1, name: 'りんご', price: 100}, 6 { id: 2, name: 'ばなな', price: 200}, 7 { id: 3, name: 'いちご', price: 400}, 8 { id: 4, name: 'おれんじ', price: 300}, 9 { id: 5, name: 'めろん', price: 500} 10 ], 11 order: false 12 }, 13 14 computed: { 15 computedData: function() { 16 console.log("computedData") 17 return Math.random() 18 }, 19 20 sorted: function() { 21 return this.list.sort(function(a, b) { 22 return this.order ? b.price - a.price : a.price - b.price; 23 }.bind(this)) 24 }, 25 limited: function() { 26 return this.sorted.slice(0, this.limit) 27 } 28 }, 29 30 methods: { 31 methodsData: function() { 32 console.log("methodsData") // 2回呼ばれるみたい 33 return Math.random() 34 } 35 } 36})
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/12 10:21