sequence

At around 4am today, vuE-Next v3.0.0-beta.1 was released, which means vUE 3.0 is officially available.

  • vue: Beta
  • 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

As you can see, Vue 3.0 beta is a series of projects, including kits, Webpack plug-ins, etc. 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 Demo. Is a framework for commercializing project capabilities. This article will include the following:

  • Build vUE 3.0 project quickly based on VUE-CLI
  • Experience basic Vue 3.0 features
  • Integrate VUE-Router and VUEX 4.0

As an aside, I found a block-level BUG in VUe-router-Next when I was building the Vue 3.0 project this noon. When I wanted to give feedback in the vue-router-next project issue, I found that someone had already submitted a similar problem. Later in the evening, during the test, The bug has been fixed, which is the efficient “like” and “issue” address of the Vue team, so when you find any problems in use, you can timely feedback under the project issue, this is a reliable team!

The Vue 3.0 project is initialized

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

Vue project initialization

Step 1, install vUE – CLI:

npm install -g @vue/cli
Copy the code

Note that the following command is wrong!

npm install -g vue
npm install -g vue-cli
Copy the code

After the installation is successful, we can use the vue command to test the method:

$vue -v @vue/cli 4.3.1Copy the code

Second, initialize the VUE project:

vue create vue-next-test
Copy the code

After entering a command, a command line interaction window is displayed. Manually select Features is used here:

Vue CLI v4.3.1? Please pick a preset: default (Babel, eslint) ❯ Manually select featuresCopy the code

Then we checked: Router, Vuex, CSS pre-processors, and Linter/Formatter, which are all necessary to develop a business-level project:

Vue CLI v4.3.1? Please pick a preset: Manually select features ? Check the features neededforyour project: ◉ Babel Infection infection TypeScript infection Progressive Web App (PWA) Support ◉ Router ◉ Vuex ◉ CSS pre-processors nut Linter/Formatter infection Unit Testing infection of E2E TestingCopy the code

Note: The Vue 3.0 project currently needs to be upgraded from the Vue 2.0 project, so in order to upgrade directly to the Vue 3.0 bucket, we need to check the Router and Vuex during the Vue project creation process, so avoid writing the initialization code manually

After press Enter, the dependency will be automatically installed. To speed up the installation, we can use Taobao source to speed up the initialization speed:

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

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

. ├ ─ ─ the README. Md ├ ─ ─ Babel. Config. Js ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ public │ ├ ─ ─ the favicon. Ico │ └ ─ ─ index. The HTML └ ─ ─ the SRC ├ ─ ─ App. Vue ├ ─ ─ assets │ └ ─ ─ logo. The PNG ├ ─ ─ components │ └ ─ ─ the HelloWorld. Vue ├ ─ ─ the main, js ├ ─ ─ the router │ └ ─ ─ index, js ├ ─ ─ store │ └ ─ ─ index. The js └ ─ ─ views ├ ─ ─ the About the vue └ ─ ─ Home. VueCopy the code

Upgrade Vue 3.0 project

At present, the creation of Vue 3.0 project needs to be realized through plug-in upgrade, vuE-CLI does not directly support, we enter the project directory, and enter the following command:

cd vue-next-test
vue add vue-next
Copy the code

After executing the above instructions, the vuE-CLI-plugin-vue-next plug-in (view the project code) is automatically installed, which does the following:

  • Install Vue 3.0 dependencies
  • Update Vue 3.0 Webpack Loader configuration to support.vue file building (this is very important)
  • Create template code for Vue 3.0
  • Vue Router and Vuex in the code will be automatically upgraded to version 4.0, and will not be upgraded if not installed
  • Automatically generate Vue Router and Vuex template code

With that done, the project is officially upgraded to Vue 3.0. Note that the plugin also supports typescript. Those of you who use typescript will have to wait.

Experience basic Vue 3.0 features

Let’s experience the development process of Vue 3.0 step by step from the perspective of project development

Create routing

In project development, we usually need to create a new page and add routing configuration. We create test.vue in/SRC /views:

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

<script>
 export default{}</script>

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

Then create the route configuration in/SRC /router/index.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: (a)= > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}, {path: '/test'.name: 'Test'.component: (a)= > import(/* webpackChunkName: "test" */ '.. /views/Test.vue')}]const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router
Copy the code

The process of initializing the Vue Router does not change much from the 3.0 version, except that we used the constructor to create the Vue Router instance instead of createRouter. The configuration method is basically the same. After configuration, we also need to add the route linking to test. vue in app. 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>
Copy the code

Launch project:

npm run serve
Copy the code

Access the project address in your browser, and you can jump to the Test page:

State and event binding

In Vue 3.0, the method for defining states was changed to something like React Hooks. Now we define a state count in test. 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>
Copy the code

Vue 3.0 initialates the state through the setup method, and defines the state by calling the ref method. Next we define an event to update the count state:

<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 = (a)= > {
        count.value++
      }
      return {
        count,
        add
      }
    }
  }
</script>
Copy the code

The add method doesn’t need to be defined in methods anymore, but instead of using count++, use count.value++. After updating the code, click the button and count will be updated:

Evaluate properties and listeners

The implementation of computed properties and listeners in Vue 3.0 relies on computed 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 = (a)= > {
        count.value++
      }
      watch((a)= > count.value, val => {
        console.log(`count is ${val}`)})const doubleCount = computed((a)= > count.value * 2)
      return {
        count,
        doubleCount,
        add
      }
    }
  }
</script>
Copy the code

Computed properties computed is a method that includes a callback function that gets its value automatically when we access the result returned by computed properties:

const doubleCount = computed((a)= > count.value * 2)
Copy the code

The watch listener is also a method that takes two arguments, both of which are function:

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

The first argument is the value of the listener. Count. Value indicates that when count. Value changes, the listener’s callback function is triggered

To get the routing

Vue 3.0 uses the getCurrentInstance method to get the current component instance, and then uses the CTX property to get the current context. CurrentRoute is used to obtain the current routing information

<script>
  import { getCurrentInstance } from 'vue'

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

Vuex integration

The Vuex integration method is as follows:

Define the Vuex state

SRC /store/index.js

import Vuex from 'vuex'

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

The syntax and API of Vuex remain basically unchanged. We create a test.a state in state, and add a method to modify the state.test.a state in mutations: setTestA

Reference the Vuex status

Second, in test.vue, use the Vuex state by calculating the attributes:

<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 = (a)= > {
        count.value++
      }
      watch((a)= > count.value, val => {
        console.log(`count is ${val}`)})const doubleCount = computed((a)= > count.value * 2)
      const { ctx } = getCurrentInstance()
      console.log(ctx.$router.currentRoute.value)
      const a = computed((a)= > ctx.$store.state.test.a)
      return {
        count,
        doubleCount,
        add,
        a
      }
    }
  }
</script>
Copy the code

Here we reference the state in Vuex by calculating attributes:

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

CTX is the current component instance we mentioned in the previous section

Updated the Vuex status

The commit method is still used to update Vuex state, as with Vuex 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 = (a)= > {
        count.value++
      }
      watch((a)= > count.value, val => {
        console.log(`count is ${val}`)})const doubleCount = computed((a)= > count.value * 2)
      const { ctx } = getCurrentInstance()
      console.log(ctx.$router.currentRoute.value)
      const a = computed((a)= > ctx.$store.state.test.a)
      const update = (a)= > {
        ctx.$store.commit('setTestA', count)
      }
      return {
        count,
        doubleCount,
        add,
        a,
        update
      }
    }
  }
</script>
Copy the code

Use ctx.code.store.mit to call setTestA and override count over state.test.a

conclusion

After experiencing Vue 3.0-beta version for the first time, I feel that Vue 3.0 has already met the necessary conditions of commercial project development, with concise syntax and excellent code readability and operation efficiency. However, due to the lack of in-depth use, more questions cannot be raised at present. We need to further discover and summarize problems in the actual project practice, and then share them with everyone.