0👍
If you simply want to pass all the parent’s attributes to a child, use Fallthrough Attributes while disabling attribute inheritance.
If you want to pick and choose a few specific members of the parent’s this
and spread them onto a child, without having to bloat the <Child />
tag by specifying each as a separate attribute, use a computed
and v-bind
:
<script>
export default {
props: ['p1', 'p2']
data: () => ({
d1: 'foo',
d2: 'bar'
}),
methods() {
m1() {
console.log('m1 was called')
},
m2() {
console.log('m2 was called')
}
},
computed: {
c1() {
return 'foo'
},
c2() {
return this.$store.state.c2
},
childAttributes() {
// extract as many things as you want from `this`
const { p1, p2, d1, d2, c1, c2, m1, m2 } = this
// return them as an object
return { p1, p2, d1, d2, c1, c2, m1, m2 }
}
}
}
</script>
<template>
<Child v-bind="childAttributes" />
</template>
If you have a really long list of members and you’re bugged by the fact you need to specify each of them twice inside childAttributes
, you might want to give pick
a chance:
import { pick } from 'lodash-es'
export default {
//...
computed: {
childAttributes() {
return pick(this, ["p1", "p2", "d1", "d2", "c1", "c2", "m1", "m2"]);
},
},
};
Motto: all we are saaayiiing… / is give pick
a chaaance…
Note: my answer focuses on Options API because that’s what you seem to be using. In Composition API you have multiple ways of doing the above but probably the most straight forward would be using a reactive
object (+ v-bind
, as above):
const props = defineProps(/*...*/)
const childAttributes = reactive({
...props,
// other refs or computed
})
- [Vuejs]-Trying to calculate the width of a text in my Nuxt App
- [Vuejs]-How to properly check authentication with Vue.js (Vue router) and Django