router&vuex&axios
vue-router
html
<script setup>
import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
// 必须先声明调用
const route = useRoute()
const router = useRouter()
// 路由信息
console.log(route.query)
// 路由跳转
router.push('/newPage')
</script>
vuex
html
<script setup>
import { useStore } from 'vuex'
import { key } from '../store/index'
// 必须先声明调用
const store = useStore(key)
// 获取Vuex的state
store.state.xxx
// 触发mutations的方法
store.commit('fnName')
// 触发actions的方法
store.dispatch('fnName')
// 获取Getters
store.getters.xxx
</script>
axios全局(getCurrentInstance使用)
getCurrentInstance 获取组件实例,调用时只能在setup与生命周期钩子中
js
// main.js
import { createApp } from 'vue'
import axios from './http'
import App from './App.vue'
const app = createApp(App)
// 配置到运行
app.config.globalProperties.$axios = axios
html
<script setup>
// setup访问 $axios
import { getCurrentInstance } from 'vue'
const { $axios } = getCurrentInstance().proxy // 获取实例proxy
console.log($axios) // 访问
</script>
<script>
// options访问 $axios
export default {
name: 'XX',
created() {
console.log(this.$axios) // 直接访问
}
}
</script>
顶层await
不需要
async
声明
html
<script setup>
const post = await fetch('/api').then(() => {})
</script>