vue3.x搭载的是vue-router 4 和 vuex 4
本节代码demo地址:demo项目链接
1、demo图
2、vue-router的用法
首先要引入vue-router暴露的api
import { useRoute, useRouter } from "vue-router";
然后在setup()函数中做相应操作
setup(){
const route = useRoute();
const router = useRouter();
const curRouterPath = router.currentRoute.value.path;
const backRouterPath = router.options.history.state.back;
}
3、vuex的用法
首先要引入vuex暴露的api
import { useStore } from "vuex";
然后在setup()函数中做相应操作
setup(){
const store = useStore();
// const hitNum = computed(() => store.state.test.hit);
const hitNum = computed(() => store.getters["test/getHit"]);
const handleClick = () => {
let num = store.state.test.hit;
store.dispatch("test/setHit", ++num);
};
}
4、还有一种获取方式,利用getCurrentInstance。但是开发环境可以,生产环境报错
我在这里也记录一下
import { getCurrentInstance} from "vue";
import { getCurrentInstance, computed } from "vue";
export default {
setup() {
const { ctx } = getCurrentInstance();
/*路由*/
const curRoutePath = ctx.$router.currentRoute.value.path;
/*vuex*/
const hitNum = computed(() => ctx.$store.state.test.hit);
return {
curRoutePath,
hitNum
};
}
};
学习笔记,以供参考,如有问题欢迎赐教!