Changes you need to know about in Vue3.0
About the lifecycle of VUe3.0
The difference between:
// Create an instance
1.Vue3 creates an instance objectconst app =Vue.createApp({})
2.Vue2c creates an instance objectconst vm=new Vue({})
// The introduction of the instance object plug-in
1.Vue3 imports the plug-in app.use(router).user(store).mount('#app')
2.Vue2 is imported into the plug-in as a parameternew Vue({
router,
store,
}).$mount('#app')
Copy the code
Custom instructions, global filters
1. The filter
A. local//vue2 local filter
<template>
<p>{{ accountBalance | currencyUSD }}</p>
</template>
<script>
export default{
filters: {currencyUSD(value){
return '$'+value
}
}
}
</script>
Vue3 partial filter modification
<template>
<p>{{accountInUSD}}</p>
</template>
<script>
export default{
computed: {accountInUSD(){
return '$'+this.accountBalance
}
}
}
</script>B. global//vue2 global filter
Vue.filter('currencyUSD'.(value) = >{
return '$'+value
})
Vue3 global filter (essentially registering a global attribute globally)
app.config.globalProperties.$filters={
accountInUSD(value){
return '$'+value
}
}
<template>
<p>{{$filters.accountInUSD(accountBalance)}}</p>
</template>
Copy the code
2. Customize commands
API for custom instructions in VUe2
Custom instruction API in VUe3
/ / 2.0
Vue.directive('highlight', {
bind(el, binding, vnode) {
el.style.background = binding.value
}
})
/ / 3.0
app.directive('highlight', {
beforeMount(el, binding, vnode) {
el.style.background = binding.value
}
})
Copy the code
3. Global components
Vue.component(component.name, component)
Copy the code
component
1. The components
DefineComponent analytical
<script>
DefineComponent can be used for manual rendering functions, TSX, and IDE tool support
// defineComponent to correctly infer the parameter types of the Setup () component
GetCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance getCurrentInstance
1. Used to add reactive state 2 to the base data type. Template application
// reactive is used to add reactive state to objects
//toRef is used to create a new ref for a property on a source responsive object to maintain a responsive connection to the properties of its source object (useful for referencing an attribute of the props passed by the parent component and maintaining a responsive connection)
//toRefs is used to convert a reactive object into a result object, where each attribute of the result object is ref (1) pointing to the corresponding attribute of the original object. 2. Automatically convert the props data to a single REF)
import { reactive,defineComponent,ref,getCurrentInstance,computed,onActivated,onBeforeMount,toRefs} from 'vue';
import {useRoute} from 'vue-router'
import { useStore } from 'vuex'
export default defineComponent({
name: 'CommonListConent'.components: {[List.name]: List},
props: {
currentPage: {
type: Number.default: () = > 1,}},Setup the second parameter {attrs,slots,emit}
Attrs can be taken to the parent component above when written on the value
//
//slots Retrieves the slots passed by the parent component
//<template>
//<van-search @update:model-value="searchValue" v-model.trim="search" shape="round" :placeholder="placeholder">
//<template v-slot:[item] v-for="(item, index) in name" :key="index">
//<slot :name="item"></slot>
//</template>
//</van-search>
//</template>
//const name=Object.keys(slots)
setup(props,{emit}) {
const instance = getCurrentInstance().proxy
const route=useRoute()
const state = reactive({
onFinished: false.onLoading: false});const root = ref(null)
const store = useStore();
const getScrollTop=computed(() = >store.getters['homeIndex/getScrollTop'])
onActivated(() = >{
if(Reflect.has(getScrollTop.value, route.path)){
root.value.$el.scrollTop = getScrollTop.value[route.path]
}
})
const onRefresh=() = >{
state.freshLoading = true;
emit('onRefresh');
},
const onLoadDisabled=computed(() = >{
return! instance.onLoad })const onRefreshDisabled=computed(() = >{
return! instance.onRefresh }) onBeforeMount(() = >{
state.onFinished = onLoadDisabled.value
})
return{
...toRefs(state),
onRefreshDisabled,
root,
}
},
emits: ['onRefresh'.'onLoad'],
})
</script>
Copy the code
2. Functional components
// Vue 2 functional components
<template functional>
<component
:is="`h${props.level}`"
v-bind="attrs"
v-on="listeners"
/>
</template>
<script>
export default {
props: ['level']}</script>
//vue3 functional components
<template>
<component
v-bind:is="`h${$props.level}`"
v-bind="$attrs"
/>
</template>
<script>
export default {
props: ['level']}</script>
// When a value is rendered on a view like $props, the view displays the original value, regardless of whether the value in props changes
Copy the code
Ref is used in vue3
1. Use
<template>
<div ref="root">This is a root element</div>
</template>
const root = ref(null)// Declare the same name as ref above, and the DOM element will be assigned to ref after initialization
Copy the code
2. V-for
2.0Writing < van - the checkbox: name ="res" :ref="`checkboxes${elemIndex}${index}`" icon-size="16px" />
<div class="left">
<img :src="res.imgUrl ? res.imgUrl : require('@/assets/images/shopLogo.png')" alt />
</div>
3.0Writing < van - the checkbox: name ="res" :ref="el=>{if(el) setCheckboxes(el,`${elemIndex}${index}`,resIndex)}" @click.stop icon-size="16px" />
<div class="left">
<img :src="res.imgUrl ? res.imgUrl : require('@/assets/images/shopLogo.png').default" alt />
</div>
Copy the code
Plugins in Vue3.0 (vueX vueRouter)
1. vuex
/ / 2.0
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import modules from './store'
Vue.use(Vuex)
const store = new Vuex.Store({
plugins: [createPersistedState({
storage: window.sessionStorage
})],
modules
})
/ / 3.0
import { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import modules from './store';
export default createStore({
plugins: [createPersistedState({
storage: window.sessionStorage,
})],
modules,
});
Copy the code
2. vuerouter
/ / 2.0 usage
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
Vue.use(Router)
const router = new Router({
routes
})
router.beforeEach((to, from, next) = > {
})
router.afterEach(() = >{})/ / 3.0 usage
import { createRouter, createWebHashHistory } from 'vue-router';
import routes from './routes'
const router = createRouter({
history: createWebHashHistory(),
routes,
});
router.beforeEach((to, from, next) = > {
})
router.afterEach(() = >{})Copy the code
Use V-bind.sync (” bidirectional binding “to a prop)
/ / 2.0
this.$emit('update:title', newValue)
//<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
<ChildComponent :title.sync="pageTitle" />
/ / 3.0
<ChildComponent v-model:title="pageTitle" />
Copy the code
Changes you need to know about Vant3 (unfinished)
1. Some misconceptions about component introduction
2. About THE API parameter declaration in VANT3.0
The first big difference between VANT2.0 and VANT3.0 is where the data is created
// The position created in vant2
export default {
data() {
return {
show: false}; },methods: {
showPopup() {
this.show = true; ,}}};// The position created in vant3
import { ref } from 'vue';
export default {
setup() {
const show = ref(false);
const showPopup = () = > { show.value = true; };
return{ show, showPopup, }; }};Copy the code
But actually vant3.0 data in creating or can be created in the data, method can be used in the method, if you don’t want to too much in the process of upgrading transformation, you can keep the source code remains the same, only change which pages at run time, will not be able to use place (remember this is just to let you quickly upgrade their projects, But it still needs to be modified later. Follow the standard.)
3. Differences between Vant3.0 Popup, ActionSheet, Dialog and Vant2. x
Vant3.0 Popup, ActionSheet, Dialog (component invocation), and Vant2 all add show to the V-model when used on the page. Upgrading requires batch modification of where you use Popup
//Popup
// Vant2
<van-popup v-model="show"> content < / van - popup >// Vant3
<van-popup v-model:show="show">content</van-popup>
//ActionSheet
// Vant2
<van-action-sheet v-model="show" :actions="actions" @select="onSelect" />
// Vant3
<van-action-sheet v-model:show="show" :actions="actions" @select="onSelect" />
//Dialog
// Vant2
<van-dialog v-model="show" title="Title" show-cancel-button> <img src="https://img01.yzcdn.cn/vant/apple-3.jpg" /> </van-dialog>
// Vant3
<van-dialog v-model:show="show" title="Title" show-cancel-button> <img src="https://img.yzcdn.cn/vant/apple-3.jpg" /> </van-dialog>
Copy the code
4. The beforeClose for Dialog on VANT3.0 is different from vant2.x
The beforeClose in VANT3 is called back as a promise
// Vant2
function beforeClose(action, done) {
if (action === 'confirm') {
setTimeout(done, 1000);
} else {
done();
}
}
Dialog.confirm({ title: 'title'.message: 'Popover contents', beforeClose, });
// Vant3
const beforeClose = (action) = >
new Promise((resolve) = > {
setTimeout(() = > {
if (action === 'confirm') {
resolve(true);
} else {
// Intercept the cancel operation
resolve(false); }},1000);
});
Dialog.confirm({ title: 'title'.message: 'Popover contents', beforeClose, });
Copy the code