Home > front end >  vue3 global variable change value on the fly
vue3 global variable change value on the fly

Time:11-24

I have a problem in my vue3 project that the global variable doesnt change its value in template

main.js

import router from './router'
import { createMetaManager } from 'vue-meta'
import i18n from './assets/js/i18n.js'
import App from './App.vue'
import { reactive } from 'vue'

import './assets/js/app.js'
import './assets/styles/app.scss'


const app = createApp(App)
  .use(router)
  .use(i18n)
  .use(createMetaManager())

app.config.globalProperties.$test = reactive({ id: 1, name: 'test' })

app.mount('#app')

and then i try to access global variable $test in component this way:

<template>
    <template v-if='$test.id'>{{ $test }}</template>
    <button class='btn btn-primary' @click='set'>change</button>
    <button class='btn btn-primary' @click='reset'>reset</button>
    <button class='btn btn-primary' @click='update'>update</button>
</template>

<script>
export default {
    methods: {
        set() {
            this.$test = { id: 3, name: 'user3' }
            console.log(this.$test)
        },
        reset() {
            this.$test = []
            console.log(this.$test)
        },
        update() {
            this.$test.name = 'updated name'
            console.log(this.$test)
        },
    },
    mounted() {
        this.$test = { id: 2, name: 'user' }
        console.log(this.$test)
    }
}
</script>

So when i go to the page i can see in browser console that global variable actually changes enter image description here

but in the template its always the same (as i did set in main.js) enter image description here

So my question is how to make global variable change on fly in template?

In future it should be an $user object, so when user login, i need to fill that $user object with data, and when user logout i want to make the object empty like this.$user = [], and in template show to user or login/register link or go to profile link through v-if v-else, something like:

<tempalte>
    <a href='/profile' v-if='$user.id'>Profile</a>
    <a href='/register' v-else'>Register</a>
</template>

Thanks for attention.

CodePudding user response:

When you set a reactive object to another object, you dropped its reactive property. You should use ref in this situation:

app.config.globalProperties.$test = ref({ id: 1, name: 'test' })
...
set() {
    this.$test.value = { id: 3, name: 'user3' }
    console.log(this.$test.value)
},
reset() {
    this.$test.value = []
    console.log(this.$test.value)
},
update() {
    this.$test.value.name = 'updated name'
    console.log(this.$test.value)
},

Btw, I don't know the reason you use a global variable but the recommended way is using state management like pinia

  • Related