Home > OS >  Watch Value In Vue.js 3, Equivalent In Pinia?
Watch Value In Vue.js 3, Equivalent In Pinia?

Time:12-06

I have a checkbox list of domain tlds, such as com, net, io, etc. I also have a search text input, where I can drill down the list of 500 or so domains to a smaller amount. For example, if I start to type co in to my search text input, I will get back results that match co, such as co, com, com.au, etc. I am using Laravel and Vue,js 3 to achieve this with a watcher. It works beautifully. How can an achieve the same within a Pinia store?

Here is my code currently:

watch: {
    'filters.searchedTlds': function(after, before) {
        this.fetchsearchedTlds();
    }
},

This is inside my vue component.

Next is the code to fetch searched tlds:

fetchsearchedTlds() {
    self = this;

    axios.get('/fetch-checked-tlds', { params: { searchedTlds: self.filters.searchedTlds } })
      .then(function (response) {
          self.filters.tlds = response.data.tlds;
          console.log(response.data.tlds);
      })
      .catch(function (error) {
          console.log(error);
      })
      .then(function () {
          // always executed
      });
  },

And finally, the code inside my Laravel controller:

public function fetchCheckedTlds(Request $request)
{
    $data['tlds'] = Tld::where('tld', 'LIKE','%'.$request->input('searchedTlds').'%')->pluck('tld');

    return response()->json($data);
}

I am converting my code to use a Pinia store and I am stuck on how to convert my vue component watcher to Pinia?

Many thanks in advance.

CodePudding user response:

To watch a pinia status, you may watch a computed attribute based on pinia or use watch getter

Your pinia may look like the one below.

~/store/filters.js

export const useFilters = defineStore('filters', {
    state: () => {
        return {
            _filters: {},
        };
    },
    getters: {
        filters: state => state._filters,
    },
    ...
}

In where you want to watch

<script setup>
import { computed, watch } from 'vue';
import { useFilters } from '~/store/filters.js';

const filters = useFilters();


// watch a computed attributes instead
const searchedTlds = computed(() => {
    return filters.filters?.searchedTlds || '';
});

watch(
    searchedTlds,
    (newValue, oldValue) {
        fetchsearchedTlds();
    }
);

// or use watch getter
watch(
    () => {
        return filters.filters?.searchedTlds || '';
    },
    (newValue, oldValue) {
        fetchsearchedTlds();
    }
);
</script>

The first parameter of watch() can be a single ref or a getter function, or an array of getter functions, for more details, please view the Watch Source Types.

  • Related