background

In front-end development, it is often necessary to obtain the current query parameter values and perform corresponding operations. This paper mainly uses vue-router@next to encapsulate tool class functions to obtain query parameter values

To solve what problems?

  1. vue-router@nextIn thequeryParameters fornull | string | null[] | string[] | Array<string | null>It’s not easy to process, and usually we just take one parameter
  2. KeepAliveWhen the component is in effect, when you switch to another page,route.queryIt can also change and cause response problems
  3. When the rollback page appears,router.queryPage data clutter caused by real-time responses

The solution

  1. Code logic processing
  2. Need to monitoronActivatedEvent, and needs to be usedisDeactivatedStatus to determine whether the page is in active state
  3. This is inissueIt has been mentioned inwatchThe increase in{ flush: 'post' }Parameter, can be processed

Actually solve the wrapping code

export function getQuery(name: string) :Ref<string> {
  const route = useRoute();
  const instance = getCurrentInstance();
  // Actual Query value
  const realQueryStr = computed(() = > {
    const v = route.query[name];
    const vv = Array.isArray(v) ? v[0] : v;
    return vv ?? "";
  });
  // The returned Query value
  const rStr = ref(realQueryStr.value);
  // Listen for the actual Query value, only modified when the component is not hidden
  watch(
    realQueryStr,
    (val) = > {
      nextTick(() = > {
        // The isDeactivated value cannot be updated in time because the KeepAlive component uses postWatch
        if(! instance? .isDeactivated) {// Update data only when the page is in effectrStr.value = val; }}); }, {flush: "post"});// Listen for component status and update the latest value when activated
  onActivated(() = > {
    rStr.value = realQueryStr.value;
  });
  return rStr;
}

Copy the code