一、指令篇
Vue3与Vue2之间生命周期函数在销毁的时候有变化
Vue2 --> Vue3
beforeDestroy --> beforeUnmount
destroyed --> unmounted
vue3中的setup() 等于vue2生命周期的beforeCreate + created
this
vue2中:一般情况下都要使用this
vue3中:因为setup函数的存在,所有的props、data等都不需要用this进行访问(vue3对 vue2绝大多数是兼容的,如果你用了vue2相关的东西,那你还是需要像vue2一样 书写)
定义全局变量的方法变化
Vue2
定义:
Vue.prototype.$http = ""
Vue.prototype.$baseUrl= "http://test"使用:
页面里面用的时候直接 this.$baseUrl
Vue3
const app = createApp({})定义
方式一:app.config.globalProperties.$baseUrl = "http://test"
方式二:app.$temp = "$temp-全局变量"+window.location.origin使用:
const { proxy,appContext } = getCurrentInstance();
方式一取用:console.error("proxy--", proxy.$baseUrl);
方式二取用:console.error("appContext--", appContext.app.$temp);
创建Vue实例变化
Vue2
import Vue from "vue"; new Vue({ el: "#app", router, store, render: (h) => h(App), });Vue3
import { createApp } from "vue"; const app = createApp(App); app.use(Vant) .use(store) .use(router) .mount("#app");
Vue3中v-model取代了.sync
变更:在自定义组件上使用v-model时, 属性、事件的默认名称变了 ( modelValue->value )
变更:v-bind的.sync修饰符在 Vue3 中被去掉了, 合并到了v-model里
新增:同一组件可以同时设置多个 v-model
新增:开发者可以自定义 v-model修饰符
<!-- Vue2中v-model --> <input v-model="searchValue"><input> <!-- 相当于 --> <input :value="searchValue" @input="searchValue=$event"><input> <!-- Vue3中v-model --> <input v-model="isVisible"></input> <!-- 相当于 --> <input :modelValue="isVisible" @update:modelValue="isVisible = $event"></input>
<!--父组件引用子组件--> <son v-model:mobileNo="mobileNo" v-model:form="selectForm" :tableDataTest="tableDataTest" @sonClick="sonClickBy" /> // 子组件emit传值给父组件 const emit = defineEmits(); // 同步修改父组件的值 const changeValue = (value)=>{ emit("update:mobileNo", value) }
Vue3同时使用
v-if
和v-for
时,v-if
比v-for
优先级更高Vue2同时使用
v-if
和v-for
时,v-for
比v-if
优先级更高
插槽使用变化
<!--Vue2插槽使用--> <div> <slot :current="toolTipData" name="test"></slot> // 具名 作用域插槽 <slot></slot> //默认插槽 </div> <!--父组件调用该组件--> <test> <template> <div>默认插槽</div> </template> // 作用域插槽 <template slot="test" slot-scope="{ current }"> <div>具名插槽</div> </template> </test> <!--Vue3插槽使用 插槽使用v-slot 简写用#--> <div> <slot name="test" :newData="slotsData"></slot> <slot></slot> </div> <!--父组件调用该组件--> <test> <template #default> // 可以写为v-slot:default #后面跟的是插槽名称 <div>默认插槽</div> </template> //作用域插槽 <template #test="{ newData }"> // 可以写为v-slot:test="newData" <p>{{ newData.aa }}</p> <p>{{ newData.bb }}</p> </template> </test>
Vue.prototype 替换为 config.globalProperties
vue2中:绑定全局的变量、方法等:Vue.prototype.$ajax = xxxx
vue3中:const app = createApp({});app.config.globalProperties.$ajax = xxxx