【问题标题】:Shared global variable/store is not working in the Vue JS共享全局变量/存储在 Vue JS 中不起作用
【发布时间】:2018-08-23 10:31:07
【问题描述】:

我正在使用 Vue js 开发一个用于学习目的的简单 Web 应用程序。我是 Vue JS 的新手,刚开始学习 Vue。我现在正在做什么,我正在尝试为所有组件共享一个状态变量,如此链接https://forum.vuejs.org/t/how-set-global-state-available-to-all-components/5947 中所示。但是,不能从不同的组件修改状态。这是我的代码。

我用这个定义为全局商店创建了一个文件

<script>
    import Vue from 'vue';

    export const globalStore = new Vue({
        data: {
            numOfViewers: 0
        }
    })
</script>

我在这样一个名为 Header 的组件中使用 globalStore 的 numOfViwers

<template>
  <header class="app-header navbar">
    <b-nav is-nav-bar class="ml-auto">
      <div class="watching">
        <span class="watching-num"><i class="fa fa-eye"></i> {{ numOfViewers }}</span>
        <span class="watching-label">Watching now</span>
      </div>
    </b-nav>
  </header>
</template>
<script>
  import { globalStore } from '../GlobalStore';
export default {
  name: 'header',
    data(){
      return {
        numOfViewers : globalStore.numOfViewers
      }
    },
    //other code
}
</script>

然后我尝试从像这样的另一个组件修改 Header 组件中的该值。

我像这样在仪表板组件中导入了 globalStore

import { globalStore } from '../GlobalStore';

在组件的mounted()事件中,我这样修改值

globalStore.numOfViewers = 100;

但是 Header 组件中的数据值没有被修改。我怎样才能让它工作?

【问题讨论】:

  • 为什么不Vuex
  • 我刚开始学习它。第一次看到Vuex这个词。谢谢

标签: javascript vue.js


【解决方案1】:

numOfViewers 移动到computed 应该会有所帮助:

computed: {
  numOfViewers() { return globalStore.numOfViewers; }
}

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2021-08-15
    • 2018-11-16
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多