###やりたいこと
コールバック部分の無名関数を、名前付きの関数に置換したいと考えています。
###元のコード
<products.js>
js
1const database = [ 2 { id: 1, name: '商品A', price: 100, content: '商品A詳細' }, 3 { id: 2, name: '商品B', price: 200, content: '商品B詳細' }, 4 { id: 3, name: '商品C', price: 300, content: '商品C詳細' } 5] 6 7export default { 8 asyncFind(id, callback) { 9 setTimeout(() => { 10 callback(database.find(el => el.id === id)) 11 }, 1000) 12 }
<Product.vue>
vue
1<script> 2 import products from 'products.js' 3 export default { 4 props: { 5 id: Number 6 }, 7 data() { 8 return { 9 item: null 10 } 11 }, 12 watch: { 13 id: { 14 handler() { 15 products.asyncFind(this.id, item => { 16 this.item = item 17 }) 18 }, 19 immediate: true 20 } 21 } 22 } 23</script>
###やってみたこと
<products.js> に以下のfind
関数を追記し、asyncFind
からcallbackを削除し、find関数を配置しました。これで、無名関数を使用していた時と同じように動くと思いましたが、<Product.vue> で商品名などが表示されませんでした。
<products.js>
js
1export default { 2 find(id) { // 追記した関数 3 return database.find(el => el.id === id) 4 }, 5 asyncFind(id) { 6 setTimeout(() => { 7 return this.find(id) // callbackを削除してfind関数を配置 8 }, 1000) 9} 10
<Product.vue>
vue
1<script> 2 import products from 'products.js' 3 export default { 4 props: { 5 id: Number 6 }, 7 data() { 8 return { 9 item: null 10 } 11 }, 12 watch: { 13 id: { 14 handler() { 15 // ここを書き換えて、asyncFindからの戻り値を、`this.item`に格納しようとした 16 this.item = products.asyncFind(this.id) 17 }, 18 immediate: true 19 } 20 } 21 } 22</script>
###質問
そもそも、<products.js> の無名関数部分を、名前付きの関数に置換するのが間違っていたのか、それとも私のコードの考え方・書き方に間違えがあるのか、ご指摘していただけると助かります。
回答1件
あなたの回答
tips
プレビュー