The introduction

It has to be said that the front end is real volume, the core developers of VUE-CLI have come out with a new CLI, Create-Vue, a scaffolding tool based on Vite2 and Vue3. Although it is still under development, many functions are not perfect, but it can be imagined that create-Vue will gradually replace vue-CLI…

First, the create – vue

1. Install

The installation is simple and requires only one NPM statement, but note that create-vue can only be installed in a folder with a non-Chinese path and Chinese name.

npm init vue@next

Some configurations:

  • The project name
  • Whether to install TS
  • Whether to install JSX
  • Whether to install the Router
  • Whether to install vuEX
  • Whether to install Cypress tests



The file directory configuration does not differ much either



Install the configuration file first after entering the folder

npm install

run

npm run dev

Home page:

2. Simple experience

Vue-cli+Vue3 is the same as vuE-CLI +Vue3, except that the template, script, and style tags of the scaffold component page have been changed.

App.vue



Embedded routines by



The page display

Second, the Pinia

Website:

pinia.esm.dev/

Pinia is a new Vue state management solution developed by Vuex team members. Mutations and module are subtracted from Pinia, and actions are used instead of mutations to complete the simultaneous asynchronous method. At the same time, each store in Pinia has its own ID, which is an independent state library, and can be directly imported into other stores by id. Its advantages:

  • Full TypeScript support.
  • Extremely lightweight (about 1KB)
  • The Actions configuration item in the Store supports both direct synchronous and asynchronous methods.
  • Modules do not need to be nested and can declare multiple stores.
  • Support Vue DevTools, SSR and Webpack code splitting.

Pinia is not intended to replace Vuex, they are used in different scenarios.

When should Pinia be used?

  1. Pinia is lightweight and small, which makes it more suitable for small to medium sized projects, or for large projects, for Vuex.
  2. Whether changes state synchronously or asynchronously in Pinia, Actions are used. If mutations and Actions are not clear in Vuex, Pinia can be used.
  3. Pinia supports TypeScript completely. We don’t add TypeScript to Vuex, so we use Pinia.

1. Install and configure Pinia

  1. Installation:

npm i pinia@next

  1. Mount Pinia in the entry file
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
/ / introduce Pinia
import { createPinia } from 'Pinia'

const app = createApp(App)

/ / use Pinia
app.use(createPinia())
app.use(router)

app.mount('#app')
Copy the code
  1. Declare stores in the SRC /stores/index.js folder.

Pinia defineStore defines the store via defineStore. The API takes two arguments. The first argument is its unique ID, which we can reference in other repositories. The second argument is the general store, getters, actions options.

defineStore(‘id’, {options})

// Introduce the Pinia definition
import { defineStore } from 'pinia'
/ / define
export const useUserStore = defineStore('user', {
    state: () = > {
        return {
            name: 'achens'}}})Copy the code
  1. Introduced and used in the component page
<script setup>
/ / introduce useUserStore
import { useUserStore } from './stores';
/ / use useUserStore
const store = useUserStore()
// Output: achens
console.log(store.name)
</script>
Copy the code

2. Use of state and getters

1. Use storeToRefs to introduce state

Use storeToRefs in Pinia to deconstruct the introduced store. StoreToRefs converts the states, getters, and Actions in the store into ref-responsive objects.

/ / introduce storeToRefs
import { storeToRefs } from 'pinia'
/ / introduce useUserStore
import { useUserStore } from './stores';
// Use storeToRefs to deconstruct the state in useUserStore
const { name } = storeToRefs(useUserStore())
// Output: ref object
console.log(name)
// Output: zhang SAN
console.log(name.value)
Copy the code

Putting it on a page is also straightforward

<template>
  <h1>Hello achens!</h1><! --<p>{{store.name}}</p> -->
  <p>Use storeToRefs:{{name}}</p>
  <router-link to="/home">Home page</router-link>
  <router-link to="/about">On the page</router-link>
  <router-view></router-view>
</template>
Copy the code

Page rendering

2. Getters in Pinia

1. Simply use Getters

Defining getters is not much different from Vuex.

import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
    state: () = > {
        return {
            name: 'Joe'.count: 5}},getters: {// Declare a getters as an arrow function, always multiplying the value of state.count by 2.
        // The first argument to getters is always state, no different from Vuex.
        doubleCount: state= > state.count * 2}})Copy the code
<template>
  <h1>Hello achens!</h1><! --<p>{{store.name}}</p> -->
  <p>Use storeToRefs:{{name}}</p>
	/ / use getters
  <p>{{ count }} -- {{ doubleCount }}</p>
  <router-link to="/home">Home page</router-link>
  <router-link to="/about">On the page</router-link>
  <router-view></router-view>
</template>
Copy the code

Page rendering

2. Access other Getters in your store

If you want to access each other in getters, you have to change the arrow function to a normal function and call other getters in the same store through this.

import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
    state: () = > {
        return {
            name: 'Joe'.count: 5}},getters: {doubleCount(state){
          return state.count * 2
      },
      // Use other getters in getters
      doubleCountPlus(state){
          return this.doubleCount + 1}})Copy the code
<template>
  <h1>Hello achens!</h1><! --<p>{{store.name}}</p> -->
  <p>Use storeToRefs:{{name}}</p>
  <p>{{ count }} -- {{ doubleCount }} -- {{ doubleCountPlus }}</p>
  <router-link to="/home">Home page</router-link>
  <router-link to="/about">On the page</router-link>
  <router-view></router-view>
</template>
Copy the code

Page rendering

3. Pass parameters to Getters

Passing a parameter to getters is a bit of a hassle. If you pass a parameter, you have to use the arrow function inside it to receive it, use it, and finally return it.

/ /... I'm not going to paste any extra code
doubleCountPlus(state, a){
  	// Use the arrow function to get the argument and return it when finished
    return a= > {
        return this.doubleCount + a
    }
}
Copy the code
<! -- Unnecessary code is not pasted --><p>{{ count }} -- {{ doubleCount }} -- {{ doubleCountPlus(5) }}</p>
Copy the code

Page rendering

4. Access Getters in other stores

Declare a new store by creating a default.js folder under SRC /store.

import { defineStore } from 'pinia'
export const useDefaultStore = defineStore('default', {
    state: () = > {
        return {
            time: 2}},getters: {calcTime(state){
            return state.time + 2}}})Copy the code

Reference useDefaultStore in default.js in index.js.

import { defineStore } from 'pinia'
// Import useDefaultStore in the same folder
import { useDefaultStore } from './default'

export const useUserStore = defineStore('user', {
    state: () = > {
        return {
            name: 'Joe'.count: 5}},getters: {doubleCount(state){
            return state.count * 2
        },
        doubleCountPlus(state, a){
            return a= > {
                return this.doubleCount + a
            }
        },
        addDefault(state){
            / / get the useDefaultStore
            const defaultStore = useDefaultStore()
            return state.count + defaultStore.calcTime
        }
    }
})
Copy the code
<p>{{ count }} -- {{ doubleCount }} -- {{ doubleCountPlus(5) }}</p>
<p>{{ addDefault }}</p>
Copy the code

Page rendering:

3. Use Actions for synchronous and asynchronous tasks

1. Process the synchronization task

If you want to change the value of state in actions, use this. XXX to retrieve the data in state and modify it.

/ /... Other code omitted
actions: {addCount(num){
        this.count += num
    }
}
Copy the code

And you cannot use storeToRefs to refer to actions methods.

// Get the method in useUserStore
const { addCount } = useUserStore()
Copy the code

The page is also used in the normal way.

<p>{{ count }}</p>
<button @click="addCount(2)">Click on the</button>
Copy the code

Each time I click count plus 2.

2. Process asynchronous tasks

There is no problem with adding timers set to asynchronous tasks.

actions:{
    addCount(num){
        setTimeout(() = > {
            this.count += num
        }, 1000)}}Copy the code

The page will now wait one second before updating data.

4. Brand management cases

Only ideas are provided here.

1. Render data

V-for renders the state (brandList) using storeToRefs structure.

2. Add data

The V-Model binds the data object (Brand) in state bidirectionally. V-on Binding Actions Click the event addBrand() to add the brand value to the brandList (using push). And clear the brand value.

3. Delete data

V-on binding Actions Click the event delBrand(ID) and pass in the brand ID of the row when clicked. Then specify the brand by id deletion (filter). this.brandList = this.brandList.filter(item => itme.id ! == id)

  • Id does not equal return
  • Id equals no return

4. Search for data

Add a keywords search field to state and bind it bidirectionally with the V-Model to its corresponding input. You then define a searchResult calculation property and filter each brand name in the brandList to return each keyword wrapped. State.brandlist. Filter (item => item.name.includes(state.keywords)) Replace brandList in V-for with searchResult.

Three, endnotes

Create-vue is similar to vue-CLI except that one uses Webpack5 as the packaging tool and the other uses Vite2 as the packaging tool. Vue2 and Vue3 are available in VUe-CLI, while create-vue is the default Vite2 + Vue3 +

Four, pit

1. Create-vue installation path cannot contain Chinese characters.

2. In pit 2, the project configuration name cannot contain a plus sign

The figure must be create-vue-pinia.

Not create-vue+pinia.



Otherwise, an error will be reported:







Original address:www.yuque.com/docs/share/…