Vue3工艺路线.查询为空

6bc51xsx  于 2022-11-17  发布在  Vue.js
关注(0)|答案(2)|浏览(253)

尝试将路由查询传递给axios请求,但它是空的.. route.query在挂载中返回空。route.query在axios中返回{"filter[city]": "Vilnius" }thennextTick不能解决问题。有任何提示吗?

import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';

import { useRouter, useRoute } from 'vue-router';

export default {
    setup() {
        const router = useRouter();
        const route = useRoute();

        onMounted(() => {
            console.log(route.query);  // log is {}
            fetchApartments();
        });
    
        function fetchApartments() {
            console.log(route.query); // log is {}
        
            axios.get('/api/apartments').then(response => {
                console.log(route.query); // log is { "filter[city]": "Vilnius" }
            });
        }
    }
}
js81xvg6

js81xvg61#

路线导航是异步的。您需要等待router.isReady以使查询可用

import {useRouter, useRoute} from 'vue-router';

export default {
  setup() {
    const router = useRouter();
    const route = useRoute();
    
    onMounted(async () => {
      await router.isReady();
      console.log(route.query);
    });
  }
}
7lrncoxx

7lrncoxx2#

更新代码,如下所示:

...
import { computed } from 'vue'
...

和内部设置()

const route = useRoute();
const query = computed(() => route.query)

这里缺少的部分是计算属性。

相关问题