代码情况
import { ref, computed, watch, reactive } from 'vue'
import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
function toggleRoute ( ) { const temprou = useRoute ( ) console. log ( temprou) ;
}
正确
import { ref, computed, watch, reactive } from 'vue'
import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router'
const temprou = useRoute ( )
import HelloWorld from './components/HelloWorld.vue'
function toggleRoute ( ) { console. log ( temprou) ;
}
总结
我使用了vue3的setup语法糖。 如果是非vue3 setup语法糖,useRouter和useRoute函数不能在setup里面的函数体内部执行,要放在顶部或者其他位置,不然作用域改变,执行后的router/route是 undefined。
非 setup 语法糖 错误写法
import { useRoute } from 'vue-router'
const useRoute1 = useRoute ( ) export default { setup ( ) { console. log ( useRoute1) ; } }
非 setup 语法糖 正确
import { useRoute } from 'vue-router'
export default { setup ( ) { const route = useRoute ( ) console. log ( route. params) }
}