vue.js - Computed property based on child components -


is possible create computed property relies on child components data? seems trivial task can't figure out...

foo component

<template>     {{ foo }} </template>  <script> export default {      computed: {         foo() {             return math.random()         }     } } </script> 

parent component

<template>     foo computed property sum: {{ sum }}     <foo v-for="n in 10"></foo> </template>  export default {      computed: {         sum() {             // return...?                     }     } } </script> 

you can, it's pretty unusual approach things, it's not best choice whatever you're trying achieve.

instead, might keep data in parent , pass component prop. if use value prop name, can nice clean syntax v-model. (you have use foos[index] due fact you can't v-model alias, in case you're generating index anyway).

new vue({    el: '#app',    data: {      foos: []    },    computed: {      sum() {        return this.foos.reduce((a, b) => + b, 0);      }    },    components: {      foo: {        template: '<div>{{ value }} <button @click="reroll">change it</button></div>',        props: ['value'],        created() {          this.reroll();        },        methods: {          reroll() {            this.$emit('input', math.floor(math.random() * 10));          }        }      }    }  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>  <div id="app">    foo computed property sum: {{ sum }}    <foo v-for="index in 10" v-model="foos[index]"></foo>  </div>


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -