如何有条件地将查询参数添加到 Vue.js 中的路由?

How to conditionally add query parameter to route in Vue.js?

我正在使用 vue-router 在单击按钮后重定向到新的 URL。如果查询参数实际已填充,我希望路由器仅将查询参数添加到 URL 中。所以如果它是 null 它应该 而不是 添加参数。

现在这没有按预期工作。看看下面的代码片段(选择每个选项并单击按钮)。

(您似乎无法在 Whosebug 上使用路由,因此请同时查看 JSFiddle 上的代码片段:https://jsfiddle.net/okfyxtsj/28/

Vue.use(VueRouter);

new Vue({
  el: '#app',
  router: new VueRouter({
    mode: 'history',
  }),
  computed: {
   currentRoute () {
     return this.$route.fullPath
    }
  },
  data () {
   return {
     some: this.$route.query.some || null      
    }
  },
  template: '<div><select v-model="some"><option :value="null">Option (value = null) which leaves empty parameter in URL</option><option value="someParameter">Option (value = someParameter) which shows parameter with value in URL</option><option :value="[]">Option (value = []) which removes parameter from URL</option></select><br><button @click="redirect">Click me</button><br><br><div>Current Path: {{ currentRoute }}</div></div>',
  methods: {
   redirect () {
     this.$router.push({
        path: '/search',
        query: {
          some: this.some || null
        }
      })
    }
  },
  watch: {
    '$route.query': {
      handler(query) {
       this.some = this.$route.query.hasOwnProperty('some') ? this.$route.query.some : null
      },
    },
  },
  watchQuery: ['some']
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>


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

somenull 时,参数仍将添加到 URL。当 some 是一个空数组时,它不会被添加到 URL.

我不想使用空数组作为默认值,因为该值应该始终是一个字符串。

那么,如果查询参数包含 null 以外的值,我该如何确保仅将查询参数添加到新路由?

使用简单的 if-elseternary 结构。也更喜欢 computed 属性 for some 而不是 watcher:

Vue.use(VueRouter);

new Vue({
    el: '#app',
    router: new VueRouter({
        mode: 'history'
    }),
    computed: {
        some() {
            return this.$route.query.some || null;
        }
    },
    data() {
        return {};
    },
    methods: {
        redirect() {
            const routeConfig = this.some
                ? { path: '/search', query: { search: this.some } }
                : { path: '/search' };

            this.$router.push(routeConfig);
        }
    },
    // Remaining config like template, watchers, etc.
});