javascript - Vue - 使全局函数的输出成为响应式(Reactive)

标签 javascript vue.js vue-component

我不久前开始使用 Vue,以及 vue-cli 和单文件组件。我有一个“问题”,我想要一个全局函数,根据该“函数”(或类)的当前(全局)设置将格式化文本返回到组件(在我的应用程序中的大多数组件中使用) 。我希望这样当设置(在本例中为 currentKey)更改时,使用此函数的所有组件都会更新值。 简而言之:currentKey 更改 - 文本被重新绘制以匹配 test 全局函数的新返回值。

涉及一些额外的逻辑,但这是我想到的最简单的例子。

在示例中,您可以看到 currentKey 变量有一个 5 秒的间隔循环,因此改变了 test 函数的输出。我希望组件每 5 秒相应更新一次。我尝试使用计算值和我发现的其他东西,但无法让它按照我想要的方式工作。

每当我更改 currentKey 变量时,如何强制组件更新?

Vue.component('component1', {
  template: '<div>{{ $test("name") }}</div>',
});

Vue.component('component2', {
  template: '<div>{{ $test("name2") }}</div>',
});

var table = {
  keyone: {
    name: 'TEST NAME FROM FIRST KEY',
    name2: 'TEST NAME 2 FROM FIRST KEY',
  },
  keytwo: {
    name: 'TEST NAME FROM <b>SECOND</b> KEY',
    name2: 'TEST NAME 2 FROM <b>SECOND</b> KEY',
  }
};
var currentKey = 'keyone';

Vue.prototype.$test = function(name) {
  return table[currentKey][name];
};

setInterval(function() {
  if(currentKey == 'keyone')
    currentKey = 'keytwo';
  else currentKey = 'keyone';
  console.log('Key changed to', currentKey);
}, 5000);

new Vue({
    el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <component1></component1>
  <component2></component2>
</div>

最佳答案

react 性与对象的属性有关。当一个对象是可观察的时,Vue 可以跟踪其属性的读写。

因此,您需要做的就是将 currentKey 设置为可观察对象的属性,然后所有反应性魔法就会生效。

只要您使用 Vue 2.6,您就可以直接使用 Vue.observable 创建可观察对象。在早期版本中,您需要创建一个虚拟 Vue 实例并使用 data 函数将 react 性应用于对象。

Vue.component('component1', {
  template: '<div>{{ $test("name") }}</div>',
});

Vue.component('component2', {
  template: '<div>{{ $test("name2") }}</div>',
});

var table = {
  keyone: {
    name: 'TEST NAME FROM FIRST KEY',
    name2: 'TEST NAME 2 FROM FIRST KEY',
  },
  keytwo: {
    name: 'TEST NAME FROM <b>SECOND</b> KEY',
    name2: 'TEST NAME 2 FROM <b>SECOND</b> KEY',
  }
};

var config = Vue.observable({
  currentKey: 'keyone'
});

Vue.prototype.$test = function(name) {
  return table[config.currentKey][name];
};

setInterval(function() {
  if(config.currentKey == 'keyone')
    config.currentKey = 'keytwo';
  else config.currentKey = 'keyone';
  console.log('Key changed to', config.currentKey);
}, 5000);

new Vue({
    el: '#app',
});
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
  <component1></component1>
  <component2></component2>
</div>

该示例仅包含渲染更新,但也会触发任何计算属性,就像 data 属性更改一样。

https://v2.vuejs.org/v2/api/#Vue-observable

关于javascript - Vue - 使全局函数的输出成为响应式(Reactive),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58463679/

相关文章:

javascript - 使用 Nuxt/Vue.js 划桨

javascript - 什么是 $cacheFactory?

javascript - 以交互模式在 qwebview 中打开 plotly

javascript - 是否可以获取网页中所有已加载资源的网络大小?

javascript - 模态不显示在 vue.js 中

javascript - 滚动时 Material VueJS 组件未固定在底部页面

vue.js - this.$root 在组件中是什么意思?

javascript - 是否有关于如何构建简单的富文本编辑器的真正基础教程?

vue.js - 电子邮件验证 n vuetify.js

javascript - Vue JS 组件如何在 Twig x 模板文件中工作