javascriptvue.jsstorehtml-framework-7

How Do I Watch Variable in Framework7 Store


I started building my app using the new built in store system and Im trying to avoid using vuex. I have a variable that changes frequently. I have used the following code when working with vuex.

store.watch((state) => state.status, (newValue) => { self.status= newValue; });

I am hoping there is a way to do it without vuex. Any help is greatly appreciated.

<template>
  <f7-navbar>
    <f7-nav-left>
      <f7-link icon="icon-bars" href="/leftsidebar/" data-ignore-cache="true">
         <f7-icon ios="f7:menu" md="material:menu" aurora="f7:menu"></f7-icon>
      </f7-link>
    </f7-nav-left>
    <f7-nav-right>
      <f7-link icon="icon-bars" href="/connect/" data-ignore-cache="true">
         <f7-icon ios="f7:globe" md="material:public" aurora="f7:globe"></f7-icon>
      </f7-link>
      <f7-link icon="icon-bars" href="/rightsidebar/" data-ignore-cache="true">
         <f7-icon ios="f7:gear_alt_fill" md="material:settings" aurora="f7:gear_alt_fill"></f7-icon>
      </f7-link>
    </f7-nav-right>
  </f7-navbar>
</template>
<script>
  import store from '../js/store';
  export default {
    name: "pageheader",
    props: {
      f7router: Object,
    },
    data() {
      return {
        offline:true
      };
    },
    mounted(){
      var self = this;
      self.offline = store.state.offline;

      // This is where I am trying to create the watcher
      store.watch((state) => state.offline, (newValue, oldValue) => { 
         self.offline = newValue; });
      }
  };
</script>

Update: I have included an example of a header component where I wish to watch the offline status in my store.


Solution

  • Presumably, your value store.state is a reactive object created by either Vuex or hand-rolled using Vue.observable(). Beyond that, you'll want to make sure that your watcher gets destroyed when the component is destroyed. This can be achieved if you use Vue's this.$watch() API instead:

    <script>
    import store from '../js/store';
    export default {
      // ...
      mounted(){
        var self = this;
    
        // Keep `offline` in sync with store
        var off = self.$watch(
          () => store.state.offline,
          (newValue) => (self.offline = newValue),
          { immediate: true }
        );
      }
    };
    </script>
    

    If you're using Framework7's Store, then you'll need to use their useStore helper to get a reactive reference to your state:

    <script>
    import { useStore } from "framework7-vue"
    import store from "../js/store"
    
    export default {
      setup() {
        const offline = useStore(store, "offline")
    
        return { offline }
      }
    }
    </script>
    

    See: Usage with Vue Components