Reputation: 35194
Vue components exposes this.$data
. Is there any way to access computed properties in a similar fashion?
They are not exposed on $data
, and there is no such thing as this.$computed
Upvotes: 2
Views: 2644
Reputation: 1255
There is a way.
const app = Vue.createApp(yourVueModelObj);
let appObject = await app.mount('#yourHtmlDomElement');
let value = appObject.$['ctx'].yourComputedProperty
Upvotes: 1
Reputation: 55634
There's no built-in way to access an object with the computed properties of a Vue instance.
If you really want an object of computed property name and values for testing purposes you could define your own $computed
property using the information in the _computedWatchers
property. This might be finicky and I wouldn't use it in production code.
Object.defineProperty(Vue.prototype, '$computed', {
get() {
let computed = {};
Object.keys(this._computedWatchers).forEach((key) => {
computed[key] = this._computedWatchers[key].value;
})
return computed;
}
})
new Vue({
el: '#app',
data() {
return {
foo: 1,
}
},
computed: {
bar() {
return this.foo * 2;
}
},
mounted() {
console.log(this.$computed)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">{{ bar }}</div>
Upvotes: 3