vue3 生命周期函数
| setup | |
| beforeCreate | 生成之前 |
| created | 生成之后 |
| beforeMount | 组件内容被渲染到页面之前 |
| mounted | 组件内容被渲染到页面之后 |
| beforeUpdate | 当data中的数据发生变化前 |
| updated | 当data中的数据发生变化后 |
| beforeUnmount | VUE实例与元素解除绑定前 |
| unmounted | VUE实例与元素解除绑定后 |
全局变量
vue2 中 写法 Vue.prototype.$appName = ‘My App’
方法1
import { provide, inject } from 'vue'
//设置变量
provide('globalVar', 2212121)
// 获取变量
inject('globalVar')
方法2
//设置
this.$app.config.globalProperties.$globalVariable = 'My Awesome App'
//获取
const { proxy } =getCurrentInstance();
console.info(proxy.$globalVariable);
vuex 状态管理 换成pinia
pinia中没有了mutations和modules,pinia不必以嵌套(通过modules引入)的方式引入模块,因为它的每个store便是一个模块,如storeA,storeB… 。在我们使用Vuex的时候每次修改state的值都需要调用mutations里的修改函数(下面会说到),因为Vuex需要追踪数据的变化,这使我们写起来比较繁琐。而pinia则不再需要mutations,同步异步都可在actions进行操作,至于它没有了mutations具体是如何最终到state变化的
注意:不能使用箭头函数定义action,因为箭头函数绑定外部this
import { useCounterStore } from '@/stores/counter'
export default {
}
# vue2
this.$store.dispatch('Login', this.loginForm)
# vue3
import { userStore } from '@/store/user'
userStore().Login(this.loginForm)
slot写法调整
// vue2
slot="content"
// vue3
v-slot:content
v-mdoel
vue2的写法
// 父组件
<my-component v-model="val" />
<my-component :value="val" @input="val = arguments[0]" />
// 子组件
<template>
<input type="text" :value="val" @input="updateInput" />
</template>
<script>
export default {
props: {
val: String
}
methods: {
updateInput(e) {
this.$emit("input", e.target.value)
}
}
}
</script>
vue3 支持多个v-model
// 父组件
<validate-input :rules="emailRules" v-model="emailVal" v-model:title="title"></validate-input>
// 子组件
<input type="text" :value="modelValue" @input="updateVal" />
// 1、定义prop属性参数
const props = defineProps({
modelValue: string; // 默认的v-model
});
// 2、定义emit名称,update+prop属性
const emit = defineEmits(['update:modelValue']);
// 3、绑定input事件,修改提交父组件修改属性值,checked事件同理
emit('update:modelValue', targetVal);
watch
vue3 写法
import {watch} from "vue";
watch(()=>props.modelValue,(newValue)=>{
value.value = newValue
},{ immediate: true, deep: true })
this.$refs.xxx
vue2 中可以通过`this.$refs.xxx`获取页面组件 vue3中如何获取
// 这边变量的名字需要和上面ref的一致。如何直接打印formRef,这个时候会是 undefined
// 因为页面组件还没有挂载完成,所以需要在挂载完成之后才能正常使用。
const formRef= ref();
// 调用子组件函数
// 第一步子组件需要暴露函数
defineExpose({
函数名称
})
// 第二步 通过ref.value 调用
formRef.value.函数名称
vue3中的provide和inject
vue2中我们可以通过provide 和 inject来实现祖孙组件之间的数据传递
// 父暴露对象
provide("itemRegister",itemRegister)
// 子组件调用
const itemRegister = inject("itemRegister")
对外暴露属性或方法
defineExpose({
close
})