I'm finding a solution to async computed method in Components:
Currently, my component is:
<div class="msg_content"> {{messages}} </div> <script> export default { computed: { messages: { get () { return api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }}) .then(response => response.data) } } }, } </script>
Result: {}
How to rewrite it in Promise
mode? Because I think we can async computed by writing into Promise mode.
This feature is synchronous. However, the vue-async-computed package allows you to create and consume asynchronous computed properties in your components by binding the resolved value of a Promise to a component property.
To use async and await in Vue. js, we can add async and await in our component methods and hooks. to make the created hook an async method. We use await to wait for the getA method to finish before running the rest of the code.
The resulting AsyncComp is a wrapper component that only calls the loader function when it is actually rendered on the page. In addition, it will pass along any props and slots to the inner component, so you can use the async wrapper to seamlessly replace the original component while achieving lazy loading.
You might know Vue updates reactively: when you change a value, the DOM is automatically updated to reflect the latest value. Vue does these updates asynchronously. In contrast, a test runner like Jest runs synchronously. This can cause some surprising results in tests.
Computed properties are basically functions that cache their results so that they don't have to be calculated every time they are needed. They updated automatically based on the reactive values they use.
Your computed does not use any reactive items, so there's no point in its being a computed. It returns a Promise now (assuming the usual behavior of then
).
It's not entirely clear what you want to achieve, but my best guess is that you should create a data item to hold response.data
, and make your api.get
call in the created
hook. Something like
export default { data() { return { //... messages: [] }; }, created() { api.get(`/users/${this.value.username}/message/`, { 'headers': { 'Authorization': 'JWT ...' } }) .then(response => this.messages = response.data); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With