Vue3.0+vue-router-next + vuex4.0 +typescript

Vue3.0

Vue3.0 is a brand new Vue version that just released a beta version in April 2020

project address:

https://github.com/kaiqiangren/vue-next-ts-preview

1. Comparison of Vue3.0 and Vue2.0:

advantage:

  1. Expose most of the APIs in Vue to the outside, so that Vue has the ability to develop large-scale projects, such as compile compilation APIs, etc.
  2. Webpack’s treeshaking support is friendly
  3. Use Proxy to define responsive variables, and improve performance by 2-3 times
  4. The composition-api plugin can be used alone in Vue2.0, or directly used to develop plugins
  5. More friendly to typescript support
  6. Facing the future: For You Yuxi’s recently innovated vite development server (abandoning webpack, the bottom layer is a high-performance development server with Koa framework), directly use the Vue3.0 syntax

Disadvantages:

  1. Only supports IE11 and above
  2. For developers who are accustomed to the Vue2.0 development model, it increases the mental burden and tests the developer’s code organization ability

At the same time, it is also an opportunity for ability improvement. I especially like the original design of the Vue author: let developers grow with the framework!

Second, the correct way to open Vue3.0

1. Project construction

  1. You need to install the latest scaffolding of vue-cli4. You can install/update the scaffolding version by executing the following npm command
npm i @vue/cli -g
  1. Then after creating the project, execute vue add vue-next to add Vue3.0 to the project
vue create [projectName]
cd [projectName]
vue add vue-next
  1. The following example is a dependency of a project developed using typescript + Vue3.0, which can also be used directly
{
  "name": "vue-next-ts-preview",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "dev": "vue-cli-service serve"
  },
  "dependencies": {
    "core-js": "^3.6.4",
     "normalize.css": "^8.0.1",
     "vue": "^3.0.0-beta.14",
     "vue-router": "^4.0.0-alpha.12",
     "vuex": "^4.0.0-beta.2"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.26.0",
    "@typescript-eslint/parser": "^2.26.0",
    "@vue/cli-plugin-babel": "~4.3.0",
    "@vue/cli-plugin-eslint": "~4.3.0",
    "@vue/cli-plugin-router": "~4.3.0",
    "@vue/cli-plugin-typescript": "~4.3.0",
    "@vue/cli-plugin-vuex": "~4.3.0",
    "@vue/cli-service": "~4.3.0",
    "@vue/compiler-sfc": "^3.0.0-beta.1",
    "@vue/eslint-config-typescript": "^5.0.2",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0-alpha.0",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "typescript": "~3.8.3",
    "vue-cli-plugin-vue-next": "~0.1.2"
  }
}

2. Use documents

  1. Project entry main.ts
import { createApp } from 'vue';
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

3. Grammar related

  1. Reactive variable declaration
Import  {  REF ,  reactive  }  from  'VUE' 
// way: the incoming value can be of any type must be used when changing the value of the value attribute, Example 2 = refData.value 
const  RefData  =  REF ( 0 )

// Method 2: You can only pass in the value of the reference type 
const  data  =  reactive ( { 
  tableData : [ 
    { 
      name : '
    名1' } 
  ] 
} )

// Use the front responsive variable, the function must be performed in the setup file Vue / return out 
setup  ( The props ,  context ){
  return {
    refData,
    data
  }
}
  1. computed
import { watch, watchEffect, computed } from 'vue'

// 1\. Create a read-only computing property 
const  computedCount  =  computed ( ( )  =>  count . Value  +  1 )

// 2\. Create a readable and writable computing property 
const  computedCount2  =  computed ( { 
      get : ( )  =>  writeCount . Value  +  2 , 
      set : ( val )  =>  { 
        return  writeCount . Value  =   val  +  2 
      } 
} )

// You can modify the computed value directly, but you cannot modify it in Vue2.x 
// computedCount2 = 123
  1. watch & watchEffect
Import  {  REF ,  Watch ,  watchEffect  }  from  'VUE' 
const  COUNT  =  REF ( 0 ) 
// watchEffect automatically collects responsive dependent 
watchEffect ( ( )  =>  Console . log ( COUNT . value ) )

// Monitor the specified basic type data 
watch ( count ,  ( now ,  prev )  =>  { 
      console . Log ( now ,  prev ,  'count' ) 
} )

const  data  =  reactive ( { 
  tableData : [ 
    { 
      name : '
    名1' } 
  ] 
} ) 
// To monitor the reactive variable created by reactive, you can directly monitor the object, you must use the inline function 
watch ( ( )  =>  data . tableData ,  ( now ,  prev )  =>  { 
   console . log ( now ,  prev ,  'tableData' ) 
} )

// Monitor multiple parameters-can not be used in composition-api 
let  position  =  reactive ( { 
    x : 1 , 
    y : 1 
  } ) 
 watch ( [ 
        ( )  =>  position . X , 
        ( )  =>  position . Y , 
      ] ,  ( [ x1 ,  y1 ] ,  [ nx1 ,  ny1 ] )  =>  { 
        console . log ( 'x1,y1',  x1 ,  y1 ) 
        console . log ( 'nx1,ny1' ,  nx1 ,  ny1 ) 
      } , 
      { 
        flush : 'post' ,  // default, triggered after the view is rendered 
        // flush:'pre', // is rendered in the view Triggered before 
        // flush:'sync' // non-blocking, triggered asynchronously 
      } )
  1. provide & inject
import { reactive, provide , inject} from 'vue'

const  data  =  reactive ( { 
  tableData : [ 
    { 
      name : '
    名1' } 
  ] 
} ) 
// root/parent component 
// provide If the responsive variable is provided here, inject will also trigger the response 
provide ( 'provideName' ,  'provideData' ) 
provide ( 'provideReactive' ,  data . tableData )

// Child/grandchild component 
setup  ( ) {
  const provideData = inject('provideName')
  const provideReactive = inject('provideReactive')
  return {
    provideData,
    provideReactive
  }
}
  1. Life cycle
Vue3.0 life cycle description corresponding Vue2.0 life cycle
setup | The life cycle of the initialization data phase, between beforeCreate and created is equivalent to the combination of beforeCreate and created
onBeforeMount | beforeMount before component mounting
onMounted | The instance is mounted mounted
onBeforeUpdate | beforeUpdate before responsive data changes
onUpdated | Responsive data change completed updated
onBeforeUnmount | beforeDestroy before the instance is destroyed
onUnmounted | The instance has been destroyed destroyed
onErrorCaptured | Error data capture--
  1. routing
// How to use route interceptor inside the component 
import  {  useRouter ,  useRoute  }  from  "vue-router"

setup() { 
  // In-component routing 
  const  router  =  useRouter ( ) 
  router . BeforeEach ( ( to ,  from ,  next )  =>  { 
    next ( ) 
  } ) 
  // In-component routing information 
  const  route  =  useRoute ( ) 
}

7.vuex

Create Store

import { createStore } from 'vuex'

const store = createStore({
  state: {
    userInfo: {
      name:'renkq'
    }
  },
  mutations: {
    getUserInfo (state, name) {
      state.userInfo.name = name
    }
  },
  actions: {
    asyncGetUserInfo ({ commit }) {
      setTimeout(() => {
        commit("getUserInfo", +new Date() + 'action')
      },2000)
    }
  },
  getters: {
    userInfoGetter (state) {
      return state.userInfo.name
    }
  }
})

export default store

Use store in the component

import {
  useStore,
  // mapState,
  // mapMutations,
  // mapActions,
  // mapGetters
} from 'vuex'

export default {
  name: 'self',
  setup() {
    const store = useStore()
    console.log(store, 'store')
    console.log(store.getters, 'getters')
    const state = store.state
    const getters = store.getters
    // console.log(mapState(store.state),'mapState')
    // console.log(mapMutations(store._mutations),'mapMutations')
    // console.log(mapActions(store._actions),'mapActions')
    // console.log(mapGetters(store.getters),'mapGetters')
    const methods = {
      // 处理commit
      handleMutation: () => {
        store.commit('getUserInfo', +new Date)
      },
      // 处理dispatch
      handleAction: () => {
        store.dispatch('asyncGetUserInfo')
      }
    }
    return {
      state,
      getters,
      ...methods
    }
  }
}
  1. v-model
// When customizing the v-model component, you need to use the update:modelValue event to trigger 
setup ( props ,  { emit } ){
   const handleClick = () => {
      emit('update:modelValue', params)
   }
   return {
      handleClick
  }
}
  1. directive

Define instructions

Import  {  ObjectDirective  }  from  'VUE' 
// declare ObjectDirective instruction type to use, because the internal source type description specifies the default 
Export  const  customDirective : ObjectDirective  =  { 
  beforeMount ( EL ,  Binding ,  the vnode ,  prevVnode )  { 
    Console . log ( EL ,  binding ,  vnode ,  prevVnode ) 
  } , 
  mounted ( )  {  console . log ( 'mounted') },
  beforeUpdate() { console.log('beforeUpdate') },
  updated() { console.log('updated') },
  beforeUnmount() { console.log('beforeUnmount') },
  unmounted() { console.log('unmounted') }
}

Global registration instructions

const app = createApp(App)
app.use(router)
app.use(store)
app.directive('custom', customDirective)
app.mount('#app')

Instructions for use in components

import { customDirective } from '../../directive/directive'
export default {
  setup() {
    return {}
  },
  directives: {
    custom: customDirective
  }
}
  1. nextTick
import { nextTick, onBeforeMount } from 'vue'

{
  setup () {

    onBeforeMount(() => {
      nextTick(() => {

      })
    })

  }
}
  1. DefineAsyncComponent & defineComponent

The difference between synchronous components and asynchronous components: synchronous components: automatically loaded when the component is loaded; asynchronous components: loaded when the component is rendered;

// One, define the synchronization component 
const  syncComponent  =  defineComponent ( { 
  setup  ( )  { 
    return  ( )  =>  `I am a synchronization component`} 
  } 
)

// Second, define asynchronous components 
// Method 1 
const  asyncComponent  =  defineAsyncComponent ( { 
  loader : ( )  =>  import ( "./asyncComponents.vue" ) , 
  loadingComponent : loadingComponent , 
  errorComponent : loadingComponent , 
  delay : 2000 , 
  timeout : 3000 
} ) ; 
// Method 2 
const  asyncComponent  =  defineAsyncComponent ( ( )  =>  import('./syncComponents.vue'));

Download Details:

Author: kaiqiangren

Source Code: https://github.com/kaiqiangren/vue-next-ts-preview

#vue #vuejs #javascript

Vue3.0+vue-router-next + vuex4.0 +typescript
71.65 GEEK