1. 如何在vue中集成ts
yarn add typescript 进行安装
vite—>vue/vue-ts
就可以直接写ts代码了
可以学习下typescript—》点击蓝色字体跟我一起快速入门ts哦
学了typescript之后再用ts的写法来写vue组件代码
2. composition API 中 使用vue-router
由于在setup中不能使用this, 因为setup在初始化之前执行的,所以setup无法访问this
setup是一个独立的钩子函数,不会依赖vue实例组件,如果用到外部函数,都需要从外部获取
不能再直接访问 this.r o u t e r 或 t h i s . router 或 this.router或this.route 作为代替,我们使用useRouter和useRoute函数
2.1创建路由
// 引用两个函数,一个是创建路由对象,一个是路由模式 import {createRouter,createWebHashHistory} from 'vue-router' // 导出创建路由对象 export default createRouter({ // 设置路由模式 history:createWebHashHistory(), // 路由信息对象 routes })
引用
import {useRouter,useRoute} from 'vue-router'
2.2 使用
setup(props) { const router = useRouter() //等同于this.$router const route = useRoute() //等同于this.$router }
3. composition API 中 使用vuex
- vuex也是无法使用this.$store
- 2.1 引用
import {useStore} from 'vuex'
2.2 使用
// 在组合api中是不支持辅助函数 setup() { const store = useStore() // 创建响应式对象,接受一个普通对象,返回一个响应式数据对象 const data = reactive({ iscount:computed(()=> store.state.count*2), doubelCount:computed(()=> store.getters.doubel) }) // 上下都可 // const iscount = computed(()=> store.state.count*2) // 提交mutations const cAdd=()=>{ store.commit('add') } const cAddVal=(val)=>{ store.commit('addVal',val) } const asyncAdd = ()=>{ store.dispatch('asyncAdd') } return{ ...toRefs(data), cAdd, cAddVal, asyncAdd } },