vue3组合式api基础(常用)
前言:vue3中尽量不要使用‘this’,最好使用组合式api(Composition API),如果使用uni-app的,vue3只支持ios>=10(2016年),安卓4.4版本(2013年)
1.使用store
import { useStore } from 'vuex'
const store = useStore()
//我这里仅获取state和mutations
//获取state我用的是computed
const jwq = computed( ()=> { //里面user为我的module,不是单独引入的可以不加
return store.state.user.token
})
store.commit('user/setToken' , res.data.token) //setToken为我mutations中的方法名
2.使用router
import { useRouter } from 'vue-router'
const router = useRouter()
//使用方法和vue2一致,例如:
router.push( { name : 'home' } )
3.创建对象
import { reactive , ref } from "vue";
const jwq = reactive({
name : 'jwq',
age : 24
})
const zhn = ref(null)
//reactive的取值方式就是jwq.name、jwq.age
//ref的取值方式 zhn.value
4.使用全局变量
//例如:在main.js中配置了全局变量$http
import * as http from './lib/axios.js' //这个http为我的请求配置文件
const app=createApp(App)
app.config.globalProperties.$http=http
//如何在页面使用这个$http呢?使用vue提供的 getCurrentInstance
import { getCurrentInstance } from "vue";
const currentInstance = getCurrentInstance()
const { $http } = currentInstance.appContext.config.globalProperties
//使用
$http.post('/api/sys/login',{
loginname: 'admin',
password: '123',
}).then(({data:res}) => {
if(res.code===0){
console.log('请求成功')
}
})
5.单文件组件父子传值 <script setup
<!-- son为子组件 fat为父组件 -->
<!-- fat.vue -->
<template>
<son :navList="navList" @handle="handleClick"></son>
</template>
<script setup>
const handleClick = (data)=> {
console.log(data)
}
</script>
<!--son.vue-->
<template>
<button @click="btn">点击</button>
</template>
import {defineProps,defineEmits} from 'vue'
<script setup>
const props=defineProps({
navList: {
type:Array,
default(){
return []
}
},
})
//获取值使用 props.navList
const emit = defineEmits(['handle']);
const btn = () => {
emit('handle', 'jwq')
}
//父组件直接访问子组件的值
//暴露数据参数,或者方法
defineExpose({navList})
//在父组件采用 ref的访问方式如fat.value.navList
//如果使用父孙组件传值
//父组件
import { provide } from "vue";
provide('reload', 100)
//孙组件
import { inject } from "vue";
inject('reload')
</script>
6.环境变量使用
.env.development文件下
VITE_NAME='development'
.env.production文件下
VITE_NAME='production'
//使用方法
//1.在vue文件中
import.meta.env.VITE_NAME
//2.在vue.config.js的配置文件中
import {defineConfig,loadEnv } from 'vite'
loadEnv(mode, process.cwd()).VITE_NAME==='production'
7.异步使用
import { nextTick } from "vue";
nextTick(()=>{
//要执行的异步代码
})
8、ref的使用(vue3和vue2的区别)
//在vue2中你可以使用this.$refs.***获取
//但是在vue3的setup中并没有这些东西,他是采用ref的方式获取,而且必须在onMounted中,假设ref为jwq
import {
ref, onMounted
} from "vue";
const jwq = ref( null )
onMounted(()=>{
console.log(jwq.value);
})
9、过滤器的替代(vue3和vue2的区别)
//在vue2中你可以使用过滤器来实现你想要的给你
//但是vue3已经去掉了过滤器,那么就要采用替代的方式,比如说时间过滤
{{ time | stampToTime }} //vue2的方式
{{ stampToTime(time) }} //vue3的方式
//vue3中你可以采用在setup中写方法的方式,实现替代
10、父子组件双向绑定
<!-- 父组件 -->
<father v-model="jwq"></father>
<!-- 子组件 -->
<!-- vue2写法 -->
this.$emit('input', e.target.value)
<!-- vue3写法 -->
this.$emit('update:modelValue', e.target.value)