I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the current settings of that function or class. Whenever these settings change (like the currentKey), all components using this function should automatically update with the new value.
In essence: when the currentKey changes, the text in components should reflect the updated return value from the test
global function.
This is just a basic example, there might be more complexity involved in reality.
In the provided code snippet, there's a 5-second interval that switches the currentKey variable, altering the output of the test
function. My goal is to have all components refreshed every 5 seconds according to this change. I've tried using computed values and other methods but haven't achieved the desired outcome yet.
How can I ensure that components update whenever the currentKey variable is modified?
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>