1

Is it possible to use Vue's computed property with an external object?

To show what I mean, here is a code example of how I imagine it:

<!-- Vue file -->

<template>
    <div>{{data.auth}}</div>
</template>

<script>
import {_data} form "./data"

export default {
    computed: {
        data() { return _data }
    }
}
</script>

<!-- data.js file -->

let _auth = "123";

export let _data = {
   auth: _auth
}

setTimeOut(() => _auth = "456", 2000)

What I would expect from this code is that the HTML document changes after 2000ms from "123" to "456".

But as far as I can say this doesn't work.

7
  • Are you using Vue 3 or Vue 2? Commented Jan 19, 2021 at 10:35
  • 1
    Currently 2. But it would be no problem to change to 3 Commented Jan 19, 2021 at 10:36
  • Your _data is not reactive, that's way is not reflecting it in html. Commented Jan 19, 2021 at 10:39
  • @ashwinbande what dose reactive mean, and how can i make it reactive? Commented Jan 19, 2021 at 10:41
  • 1
    Only way to make it reactive in vue2 is to change it through vue component function e.g. use setTimeout in created hook or so; in vue3 you can use reactive directly; refer vue3 documentation for that. Commented Jan 19, 2021 at 10:48

2 Answers 2

2

With Vue 3 you can import ref to track changes:

import { ref } from 'vue'

const _auth = ref('123')

export const _data = {
    auth: _auth
}

setTimeout(() => {
    _auth.value = '456'
}, 2000)

Working snippet:

const _auth = Vue.ref('123')
const _data = {
  auth: _auth
}

setTimeout(() => {
  _auth.value = '456'
}, 2000)

Vue.createApp({
  data() {
    return {
      data: _data
    }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <div>{{ data.auth }}</div>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to abstract it to js without vue dependencies?
It isn't, as far as I know. Though, what would be the reason for that? It doesn't add extra dependencies, you're just importing from an existing one
We would like to create a JavaScript api which should be compatible with vue but also possibly with other frameworks. So some kind of solution without dependencies from vue would be optimal.
Oh, I see. Only way around that (that I can think of) is using a conditional to check if Vue is being used, if so, use something similar to my answer, else, use a vanilla JS version (or whatever different framework is in use).
2

With Observables, you can make data reactive

import Vue from "vue";

let _auth = "123";
export let _data = Vue.observable({
  auth: _auth
});

setTimeout(() => {
  _data.auth = "456";
}, 2000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.