Summary vue2 0 and vue3 The difference between 0 allows you to get started quickly

1:vue3. Difference between 0 and 2.0

2.0 bidirectional data binding

Vue2.0 uses object defineProperty

Principle: by using object Defineproperty to hijack the getter and setter operations of object properties, and send a notification when the data changes

// data
let data = {
	title: '',
	// Backup data
	_data: {}
}
// Define properties
Object.defineProperty(data, 'title', {
	// Define property attributes or property methods
	// Value method
	get() {
		// console.log('get')
		// Note: the attribute cannot be taken by itself
		// return this.title
		// Return backed up data
		return this._data.title;
	},
	// Assignment method
	set(value) {
		// this points to the object
		// Note: you cannot assign values to your own attributes
		// this.title = value
		// We can store it in the backup data
		this._data.title = value;
		// console.log('set')
		// update the view
		updateView(this._data)
	}
})
// View template
let tpl = document.getElementById('app').innerHTML
// Method of updating view
function updateView(data) {
	// Processing template
	let html = tpl.replace(/{{(w+)}}/g, (match, $1) => {
		// Get data from data
		return data[$1] || ''
	})
	// update the view
	document.getElementById('app').innerHTML = html;
}

Vue3.0 data binding

Use the new features of ES6 porxy

Principle: hijack data through proxy, a new feature of ES6, and send a notice when the data changes

  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="yingaxiang" content="width=device-width, initial-scale=1.0">
      <title>vue3.0 Bidirectional data binding</title>
  </head>
  <body>
      <div>
         <input type="text" id="input">
         <span id="text"></span>
     </div>
 </body>
 </html>
 <script>
     var obj = {};
     var obj1 = new Proxy(obj, {
         // target is the first parameter obj, and receive is the returned obj (the returned proxy object)
         get: function (target, key, receive) {
             // Returns the property value
             return target[key];
         },
         set: function (target, key, newVal, receive) {
             // Perform assignment operation
             target[key] = newVal;
             document.getElementById('text').innerHTML = target[key];
         }
     })
     document.addEventListener('keyup', function (e) {
         obj1[0] = e.target.value;
     });
 </script>

Summary:

Vue2. Bidirectional binding in version x cannot detect subscript changes
proxy can hijack the whole object and return a new object

2: Create project

Students who have not created vue scaffolds or who have pulled projects down from the line can first check the current version

1: Check the current version. If it starts with 2, it means that vue-cli2 is currently used, and if it starts with 3, it means vue-cli4

vue --version

2: If the vue command is not recognized, it means that vue cli is not installed, use the following instructions to install it
Installation of version 3.0: at present, the default installation of scaffold for new projects is version 3.0

npm install -g vue-cli

If the old project is switched from version 2.0 to version 3.0, uninstall the current version and install another version
Upgrade from 2.0 to 3.0:

npm uninstall -g vue-cli

npm install -g @vue/cli

If you want to drop from the new version to the old version, you have to look here!!

From 3.0 to 2.0:

npm uninstall -g @vue/cli
npm install -g vue-cli

Project initialization

Initialization, Vue init < template name (webpack is commonly used) > [project name]

vue init webpack cli2-test

2.0 introduction to project initialization parameters

//entry name

Project name ...

//The author's information will be read from git by default

Project description ...

Author ...

//Option 1 of vue build runtime-compiler 2. Runtime only

vue build ...

//Whether to install Vue router is generally YES, eliminating the need to manually create a route

Install vue-router? ..

//Whether to use ESLint to detect code specifications. You can select different specification libraries or add specifications yourself according to options

use ESLint to link your code

//Whether to write unit test (generally not used)

Set up unit tests

//Whether to use Nightwatch for e2e test (2 for point-to-point)

Setup e2e test with Nightwatch?

//Use npm or yarn package management tools

use npm

use yarn

3.0 initialization, vue create [project name]

vue create cli3-test

?Introduction to project initialization parameters

//Select a configuration method
 please pick a perset  (Usually choose the last one Manually select features((select Properties manually) )
 //Select the features required for your project (select with spaces)
 check the features needed for your project
( ) Babel //Transcoder, which can convert ES6 code into ES5 code for execution in the existing environment. 
( ) TypeScript// TypeScript is a superset of JavaScript (suffix. js) (suffix. ts). It contains and extends the syntax of JavaScript. It needs to be compiled and output as JavaScript to run in the browser. At present, it is rarely used
( ) Progressive Web App (PWA) Support// Progressive Web application
( ) Router // vue router
( ) Vuex // vuex (state management mode of vue)
( ) CSS Pre-processors // CSS preprocessor (e.g. less, sass)
( ) Linter / Formatter // Code style checking and formatting (e.g. ESlint)
( ) Unit Testing // unit tests
( ) E2E Testing // e2e (end to end) test
 //Is the corresponding configuration file generated separately or placed in package JSON
 where do you prefer placing config for babel
 //Do you want to save the configuration you just selected
 save this as a preset for future projects?

3: Directory of projects

Vue2.0 version directory

[here is picture 001]

Vue3.x version directory

[here is picture 002]

Summary:

  • vue-cli2. There are obvious differences between 0 and 3.0 in directory structure
  • vue-cli3.0 remove the configuration file directory, config and build folders
  • At the same time, the static folder is removed and the public folder is added. When you open the hierarchical directory, you will find that index Move HTML to public
  • The 3.0 config file has been removed, but there are too many env.production and env The actual configuration of the development file, except for the file location, is no different from that of 2.0
  • If there is no config file and the domain name needs to be configured across domains, start config / index JS moved to Vue config. JS, the configuration method remains unchanged
  • The static folder is removed, the public folder is added, and the index Move HTML to public
    views folder is added in src folder to classify view components and public components

4: In version 3.0, the project environment variable configuration file is missing (dev.env.js / prod.env.js)

We can manually create configuration files for different environments in the project root directory. The specific environment variable name is determined by package The running parameters in JSON determine that the environment variables of development, production and uat versions are added as an example:

//  .env.delelopment
NODE_ENV=development
VUE_APP_MODE=development
BASE_URL=/develop
// .env.production
NODE_ENV=production
VUE_APP_MODE=production
BASE_URL=/api
 
// .env.uat
NODE_ENV=production
VUE_APP_MODE=uat
BASE_URL=/uat


Different environments send different packages. Students should configure them for reference


// package.json
----
"scripts": {
   "serve": "vue-cli-service serve",
   "build:uat": "vue-cli-service build --mode uat", // Through -- mode to run different environments, it is automatically recognized env.uat profile
   "build:production": "vue-cli-service build --mode production",
   "lint": "vue-cli-service lint"
 },

In version 3.0, there are no webpack configuration files for different environments (webpack.base.conf.js / webpack.dev.conf.js / webpack.prod.conf.js)
Similarly, we can also create vue in the root directory config. JS file to configure webpack and vue

const path = require('path')
 
module.exports = {
 publicPath: './', // Basic path, plus when packing
 outputDir: process.env.outputDir, // Output file directory
 lintOnSave: false, // Does the eslint loader check when saving
 // see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
 // webpack configuration
 chainWebpack: (config) => {
   config.resolve.symlinks(true)
 },
 configureWebpack: (config) => {
   if (process.env.VUE_APP_MODE === 'production') {
     // Modify configuration for production environment
     config.mode = 'production'
   } else {
       // Modify configuration for development environment
       config.mode = 'development'
   }
   Object.assign(config, {
     // Development and production common configuration
     resolve: {
       alias: {
         '@': path.resolve(__dirname, './src'),
         '@c': path.resolve(__dirname, './src/components'),
         '@p': path.resolve(__dirname, './src/views')
       } // Alias configuration
     }
   })
 },
 productionSourceMap: false, // Does the production environment generate sourceMap files
 // css related configuration
 css: {
   // extract: true, / / whether to use the css separation plug-in ExtractTextPlugin
   sourceMap: false, // Open CSS source maps?
   loaderOptions: {
     css: {}, // The options here will be passed to CSS loader
     less: {
       modifyVars: {
         // less vars,customize ant design theme
 
         // 'primary-color': '#F5222D',
         // 'link-color': '#F5222D',
         // 'border-radius-base': '4px'
       },
       // DO NOT REMOVE THIS LINE
       javascriptEnabled: true
     },
     postcss: {
       plugins: [
         // Convert px units to rem units
         require('postcss-pxtorem')({
           rootValue: 75, // Base of conversion (the root font of design drawing 750 is 32)
           selectorBlackList: ['.van-'], // The selector to ignore and leave as px.
           propList: ['*'], // Property that can be changed from px to rem.
           minPixelValue: 2 // Sets the minimum pixel value to replace.
         }),
         require('autoprefixer')
       ]
       // plugins: [
       //   require('autoprefixer')
       // ]
     } // The options here will be passed to the postcss loader
   }, // CSS preset configuration items are shown in https://cli.vuejs.org/zh/config/#css-loaderoptions
   // modules: false, / / enable CSS modules for all CSS / pre processor files
   requireModuleExtension: true
 },
 parallel: require('os').cpus().length > 1, // Whether to use thread loader for Babel or TypeScript. This option is automatically enabled when the CPU of the system has more than one kernel and only works on production builds.
 pwa: {}, // PWA plug-in configuration see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
 // Configuration related to webpack dev server
 devServer: {
   open: false, // Automatically open browser
   host: '0.0.0.0', // Allow external ip access
   port: 8000, // port
   https: false, // Enable https
   overlay: {
     warnings: true,
     errors: true
   }, // Errors and warnings pop up on the page
   // proxy: 'http://localhost:4000 '/ / configure cross domain processing with only one agent
   proxy: {
       '/api': {
           target: '<url>',
           ws: true,
           changeOrigin: true
       },
       '/foo': {
           target: '<other_url>'
       }
   },  // Configure multiple agents
 },
 // Third party plug-in configuration
 pluginOptions: {}

5: Another reference article on step function

https://blog.csdn.net/qq_41328247/article/details/109286022

6: Comparison of 2.0 and 3.0 life cycle functions:

2.0 cycle name

3.0 cycle name

explain

beforeCreate

setup

Before component creation

created

setup

Component creation complete

beforeMount

onBeforeMount

Before component mounting

mounted

onMounted

Component mount complete

beforeUpdate

onBeforeUpdate

Data update, before virtual DOM patching

updated

onUpdated

Data update, virtual DOM rendering completed

beforeDestroy

onBeforeUnmount

Before component destruction

destroyed

onUnmounted

After component destruction

<template>

<router-link to="/">Click here to go to the home page</router-link>

<hr>

<div class="home">

Here is a counter >>> <span class="red">{{count}}</span> <br>

<button @click="countAdd">Click add number</button>

</div>

</template>

<script>

// What life cycle you need to use will lead to what life cycle

import {

onBeforeMount,

onMounted,

onBeforeUpdate,

onUpdated,

onBeforeUnmount,

onUnmounted,

ref

} from 'vue'


export default {

// The setup function is equivalent to created in vue 2.0

setup () {

const count = ref(0)

// Other life cycles are written here

onBeforeMount (() => {

count.value++

console.log('onBeforeMount', count.value)

})

onMounted (() => {

count.value++

console.log('onMounted', count.value)

})

// Note: do not modify the values in onBeforeUpdate and onUpdated, which will cause an endless loop!

onBeforeUpdate (() => {

console.log('onBeforeUpdate', count.value)

})

onUpdated (() => {

console.log('onUpdated', count.value)

})

onBeforeUnmount (() => {

count.value++

console.log('onBeforeUnmount', count.value)

})

onUnmounted (() => {

count.value++

console.log('onUnmounted', count.value)

})

// Define a function to modify the value of count.

const countAdd = () => {

count.value++

}

return {

count,

countAdd

}

}

}

</script>

First, in vue 3.0 In, the life cycle is from vue We can export what we need to use.

Many watchers may think that they have done one thing many times, but in fact, it is not. vue provides so many life cycles, how many are we commonly used? In most components, we don't use the life cycle. Even for page level applications, onMounted may be used most.

Of course, those operations with binding time will use unbinding, so onUnmounted will be used. Other life cycles are basically unavailable under normal circumstances. Therefore, by introducing this setting, we can reduce the volume of our final compiled project. Moreover, such introduction and use makes the logic clearer.

Secondly, except for setup, other life cycle functions can be written directly in setup.

7. References to documents

  • vue2. For the instance object of new in X, everything is on this vue object. In this way, it will change whether you use it or not.
  • vue3.0 can be imported on demand with ES module imports, such as keep alive built-in components, v-model instructions, and so on.

8. Project initiation

Vue2.x version launch

npm run dev

Vue3.x version launch

npm run serve

9. Grammar

1. Use modelValue instead of V-model syntax

<input v-model="value" />

<input modelValue="value" />

2. Discard the global APInew Vue and use createApp

const app =?Vue.createApp({})

3. Discard Vue Prototype. In Vue3, we can use the following definition

const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

4. The global methods are now all on the app instance, for example:

`app.directive`,`app.use`etc.

5. Now you need to mount the root node manually

main.js


import { createApp } from 'vue'

import App from './App.vue'


createApp(App).mount('#app')

6. Vue can no longer be used nextTick/this.$ Nexttick, Vue3, you can use:

import { nextTick } from 'vue'
nextTick(() => {
  // something
})

7.Vue3 allows the template to set the key.

8. Officially discard scopedSlots. The old will not go and the new will not come.

9. The deep attribute needs to be used to monitor the change of the array, otherwise the whole array can only be monitored to be replaced.

10. Discard $children and use $ref to access sub components

11. The filter has been removed, I X, can no longer use |.

12. Remove the event API, $on,$once,$off are no longer used. The EventBus method is no longer used.

10 new TypeScript and PWA support

11: More accurate change notice

In version 2.x, Vue Set to add a property to the object, all the watcher s of the object will run again
In version 3.x, only watcher s that depend on that attribute will run again.

Keywords: Python Front-end html crawler

Added by gusaps on Mon, 07 Mar 2022 02:22:06 +0200