代码之家  ›  专栏  ›  技术社区  ›  Chris

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

  •  1
  • Chris  · 技术社区  · 6 年前

    我正在使用 vue-router null 应该的 添加参数。

    现在这不是预期的效果。查看以下代码段(选择每个选项并单击按钮)。

    (看起来你不能在Stackoverflow上使用路由,所以请看一下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>

    什么时候? some 参数仍将添加到URL。什么时候? 是空数组,它将不会添加到URL。

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

    那么,如果查询参数包含的值不是 无效的 ?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Harshal Patil    6 年前

    使用简单的 if-else ternary 构造。也更喜欢计算属性 some 代替观察者:

    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.
    });