Vue version 3.0 - let's talk

Posted by cjkeane on Fri, 28 Jan 2022 16:28:52 +0100

vue3.0 version

preface

Study vue3 0 can learn and consolidate vue2 0 knowledge points are helpful for 3.0. Come on, Sao Nian!

vue: Beta

It can be seen that the Vue 3.0 beta version is a project series, including the suite and webpack plug-ins we need in the development process. This article will take you to quickly build a project framework based on Vue 3.0, which is different from many previous Vue 3.0 demos. It is a framework with commercial project capability. This article will include the following contents:

Rapid construction of Vue 3.0 project based on Vue cli
Vue 3.0 basic feature experience
Integration of Vue router and vuex 4.0

 vue-router: Alpha
 vuex: Alpha
 vue-class-component: Alpha
 vue-cli: Experimental support via vue-cli-plugin-vue-next
 eslint-plugin-vue: Alpha
 vue-test-utils: Alpha
 vue-devtools: WIP
 jsx: WIP

Therefore, when you find problems in use, you can give feedback to the project issue in time. This is a reliable team! issue address

Vue 3.0 project initialization

The initialization process of Vue 3.0 project is similar to that of Vue 2.0. The specific steps are as follows:

Vue Project initialization

Step 1: install Vue cli:

npm install -g @vue/cli
 Note that the following command is wrong!
npm install -g vue
npm install -g vue-cli

After the installation is successful, we can use the vue command. The test method is as follows:

$ vue -V
@vue/cli 4.3.1

Step 2: initialize vue project:

vue create vue-next-test
After entering the command, the command line interaction window will appear. Here we choose Manually select features: 
Vue CLI v4.3.1
? Please pick a preset: 
  default (babel, eslint) 
❯ Manually select features 
Then we check: Router,Vuex,CSS Pre-processors and Linter / Formatter,These are necessary for the development of commercial projects:
Vue CLI v4.3.1
? Please pick a preset: Manually select features
? Check the features needed for your project: 
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
 ◉ CSS Pre-processors
❯◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing

Note: Vue 3.0 project needs to be upgraded from Vue 2.0 project at present, so in order to upgrade directly to Vue 3.0 project, we need to check Router and Vuex during the creation of Vue project, so we can avoid writing initialization code manually

The dependency will be automatically installed after entering. In order to speed up the installation, we can use Taobao source to speed up the initialization:

vue create -r https://registry.npm.taobao.org vue-next-test

After the project is created, the directory structure is as follows:

.

├── README.md
├── babel.config.js
├── package-lock.json
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
└── src
    ├── App.vue
    ├── assets
    │   └── logo.png
    ├── components
    │   └── HelloWorld.vue
    ├── main.js
    ├── router
    │   └── index.js
    ├── store
    │   └── index.js
    └── views
        ├── About.vue
        └── Home.vue
  

Upgrade Vue 3.0 project

At present, the creation of Vue 3.0 project needs to be realized through plug-in upgrade. Vue cli has not been directly supported. We enter the project directory and enter the following instructions:

cd vue-next-test
vue add vue-next

After executing the above instructions, the Vue cli plugin Vue next plug-in will be automatically installed (check the project code). The plug-in will complete the following operations:

Installing Vue 3.0 dependencies

Update the configuration of Vue 3.0 webpack loader to support vue file construction (this is very important)
Create template code for Vue 3.0
Vue Router and Vuex in the code are automatically upgraded to version 4.0. If they are not installed, they will not be upgraded
Automatically generate Vue Router and Vuex template codes

After completing the above operations, the project is officially upgraded to Vue 3.0. Note that the plug-in can also support typescript. Students who use typescript have to wait.
Vue 3.0 basic feature experience
Let's gradually experience the development process of Vue 3.0 from the perspective of project development
Create route
In project development, we usually need to create a new page and then add routing configuration. We create test.com in / src/views directory vue:

<template>
  <div class="test">
    <h1>test page</h1>
  </div>
</template>

<script>
 export default {
 }
</script>

<style lang="less" scoped>
.test {
  color: red;
}
</style>

Then in / SRC / router / index Create routing configuration in JS:

import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/test',
    name: 'Test',
    component: () => import(/* webpackChunkName: "test" */ '../views/Test.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

The process of initializing Vue Router is not much different from that of version 3.0, except that the constructor is used before. Here, createRouter is used to create Vue Router instance. The configuration method is basically the same. After the configuration is completed, we also need to create Vue Router instance in app Add link to test in Vue Route of Vue:

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/test">Test</router-link>
    </div>
    <router-view/>
  </div>
</template>

Start project:

npm run serve

Access the project address in the browser. At this time, you can jump to the Test page:

State and event binding
The method of defining state in Vue 3.0 is changed to a method similar to React Hooks. Let's test Define a status count in Vue:

<template>
  <div class="test">
    <h1>test count: {{count}}</h1>
  </div>
</template>

<script>
  import { ref } from 'vue'

  export default {
    setup () {
      const count = ref(0)
      return {
        count
      }
    }
  }
</script>

In Vue 3.0, the initialization state is defined through the setup method, and the ref method needs to be called. Next, we define an event to update the count status:

<template>
  <div class="test">
    <h1>test count: {{count}}</h1>
    <button @click="add">add</button>
  </div>
</template>

<script>
  import { ref } from 'vue'

  export default {
    setup () {
      const count = ref(0)
      const add = () => {
        count.value++
      }
      return {
        count,
        add
      }
    }
  }
</script>

The add method here no longer needs to be defined in methods, but note that when updating the count value, you can't directly use count + +, but count Value + +, after updating the code, click the button, and the value of count will be updated:

Calculate properties and listeners
The implementation of calculation properties and listeners in Vue 3.0 depends on the calculated and watch methods:

<template>
  <div class="test">
    <h1>test count: {{count}}</h1>
    <div>count * 2 = {{doubleCount}}</div>
    <button @click="add">add</button>
  </div>
</template>

<script>
  import { ref, computed, watch } from 'vue'

  export default {
    setup () {
      const count = ref(0)
      const add = () => {
        count.value++
      }
      watch(() => count.value, val => {
        console.log(`count is ${val}`)
      })
      const doubleCount = computed(() => count.value * 2)
      return {
        count,
        doubleCount,
        add
      }
    }
  }
</script>

The calculated property is a method that needs to contain a callback function. When we access the returned result of the calculated property, we will automatically obtain the value of the callback function:

const doubleCount = computed(() => count.value * 2)

The listener watch is also a method, which contains two parameters, both of which are function:

watch(() => count.value, 
  val => {
    console.log(`count is ${val}`)
  })

The first parameter is the listening value, count Value means when count When value changes, it will trigger the callback function of the listener, that is, the second parameter, which can execute the callback during listening
Get route
In Vue 3.0, get the instance of the current component through getCurrentInstance method, and then get the current context through ctx attribute, ctx$ Router is an instance of Vue Router, which contains the current route information that currentRoute can obtain

<script>
  import { getCurrentInstance } from 'vue'

  export default {
    setup () {
      const { ctx } = getCurrentInstance()
      console.log(ctx.$router.currentRoute.value)
    }
  }
</script>

Vuex integration

Vuex's integration method is as follows:
Define Vuex status

Step 1: modify Src / store / index JS file:

import Vuex from 'vuex'

export default Vuex.createStore({
  state: {
    test: {
      a: 1
    }
  },
  mutations: {
    setTestA(state, value) {
      state.test.a = value
    }
  },
  actions: {
  },
  modules: {
  }
})

The syntax and API of Vuex are basically unchanged. We created a test in state A status, adding and modifying state in changes test.a status method: setTestA
Reference Vuex status

The second step is to Test.vue In, by calculating attributes Vuex Status:
<template>
  <div class="test">
    <h1>test count: {{count}}</h1>
    <div>count * 2 = {{doubleCount}}</div>
    <div>state from vuex {{a}}</div>
    <button @click="add">add</button>
  </div>
</template>
<script>
  import { ref, computed, watch, getCurrentInstance } from 'vue'

  export default {
    setup () {
      const count = ref(0)
      const add = () => {
        count.value++
      }
      watch(() => count.value, val => {
        console.log(`count is ${val}`)
      })
      const doubleCount = computed(() => count.value * 2)
      const { ctx } = getCurrentInstance()
      console.log(ctx.$router.currentRoute.value)
      const a = computed(() => ctx.$store.state.test.a)
      return {
        count,
        doubleCount,
        add,
        a
      }
    }
  }
</script>

Here, we reference the state in Vuex by calculating the attribute:

const a = computed(() => ctx.$store.state.test.a)

ctx is the current component instance we mentioned in the previous section
Update Vuex status
The commit method is still used to update Vuex status, which is consistent with Vuex version 3.0:

<template>
  <div class="test">
    <h1>test count: {{count}}</h1>
    <div>count * 2 = {{doubleCount}}</div>
    <div>state from vuex {{a}}</div>
    <button @click="add">add</button>
    <button @click="update">update a</button>
  </div>
</template>

<script>
  import { ref, computed, watch, getCurrentInstance } from 'vue'

  export default {
    setup () {
      const count = ref(0)
      const add = () => {
        count.value++
      }
      watch(() => count.value, val => {
        console.log(`count is ${val}`)
      })
      const doubleCount = computed(() => count.value * 2)
      const { ctx } = getCurrentInstance()
      console.log(ctx.$router.currentRoute.value)
      const a = computed(() => ctx.$store.state.test.a)
      const update = () => {
        ctx.$store.commit('setTestA', count)
      }
      return {
        count,
        doubleCount,
        add,
        a,
        update
      }
    }
  }
</script>

Here, after we click the update a button, the update method will be triggered. At this time, CTX$ store. Commit calls the setTestA method and overwrites the value of count with state test. Value of a

Author: Xiaoxin children's shoes (turn)
Link: article
Source: Nuggets

summary

After experiencing the Vue 3.0-beta version for the first time, I feel that Vue 3.0 has met the necessary conditions for commercial project development, with refined syntax and excellent code readability and operation efficiency. However, due to the lack of in-depth use, no more questions can be raised at present. We need to further find and summarize the problems in the actual combat of the project, and then share and communicate with you.

For example, the above is what we're going to talk about today. If this article is helpful to you, please praise it. Study together and come on

I'm Xiao Xin,
Bye ~ ~

Topics: Javascript Front-end Vue