The syntax difference between Vue2 and Vue3

1. Create Vue2 project

—Use @vue/cli scaffolding to quickly create projects (packaging method webpack) —Vetur plug-in (VS code)

>>>npm create project name

—npm run serve project startup command

The project structure is as follows

Vue2The basic page numberStructure is as follows HTML-js-CSS

<template>
  <div id="app">
    <span>This is a vue2 page</span><br/>
    <span>Age is {<!-- -->{age}} years old</span><br/>
    <button @click="ageChange">Button</button>
  </div>
</template>

<script>
export default{
  name: "HomeView",
  //Define data
  data(){
    return{
      age:1
    }
  },
  //Define method
  methods:{
    ageChange(){
      this.age + = 1
    }
  },
  //Computed property
  computed:{

  },
  //Listen properties
  watch:{

  }
 }
</script>


<style>
</style>

————————————————-page The elements are as follows———————————————— ————-

—Three situations for displaying data

  • v-html
  • v-text
  • {{ }}

snippet generator snippet generator

Custom code generation template shortcut keys

2.Vue2 related syntax

2.1 Computed properties

  • Use operators in interpolation expressions to perform computed properties
  • Computed properties in Method
  • Operate in Computed Properties

Interview question—The difference between method and computed

  • computed has cache and is an attribute
  • Method is a function. To use it, you need to call FUN()
<template>
  <div id="app">
    <span>This is a vue2 page</span><br/>
    <span>Two ways to test computed properties</span><br/>
    {<!-- -->{ name1 + name2}}<br/>
    {<!-- -->{ changeName() }}<br/>
    {<!-- -->{Name}}<br/>
     
  </div>
</template>

<script>
export default{
  name: "HomeView",
  data(){
    return{
      name1:"lihua",
      name2:"zhangwei"
    }
  },
  methods:{
    //Method 1: Define the method
    changeName(){
      return this.name1 + this.name2
    }

  },
  computed:{
    //Method 2: Calculated properties
    Name(){
      return this.name1 + this.name2
    }
  },
  watch:{

  }
 }
</script>


<style>
</style>

2.2 Monitoring attributes

v-model data two-way binding

v-model can listen to the data in data(), and can also listen to the computed Computed attribute data

But cannot listen to the method

<template>
  <div id="app">
    <span>This is a vue2 page</span><br/>
    <span>Test attribute monitoring</span><br/>
    <input type="text" v-model="name">
  </div>
</template>

<script>
export default{
  name: "HomeView",
  data(){
    return{
      name:"hello"
    }
  },
  methods:{
  },
  watch:{
    name(newValue,oldValue) {
       console.log(newValue,oldValue);
    }
  }
 }
</script>


<style>
</style>

————————————————– ——–Console results—————————————— ————-

2.3 related instructions

v-bind: xx = ” ” Dynamically bind the xx attribute

v-bind: title —> Dynamically bind the title attribute —> Abbreviation: title

<template>
  <div id="app">
    <span>vue2-Testing dynamic binding css styles</span><br/>
    <div v-bind:style="s1">Dalian City</div>
    
  </div>
</template>

<script>
export default{
  name: "HomeView",
  data(){
    return{
     s1:{color:"green"}
    }
  }
 }
</script>


<style>
</style>

—The page effect is as follows—

v-on binds event listeners to HTML elements abbreviation @

2.4 Defining attributes

var-let-const—Keywords that define attributes

var: attributescan be declared repeatedly, let and const attributes cannot be declared repeatedly

var and let declare variables, and const declares constants

The constant declared by const cannot be changed (memory fixed), but its internal properties can be changed.

2.5 Conditional Rendering

v-if renders elements if true, otherwise false

Can be used with v-else-if and v-else

Note: v-else must be used after v-else-if, and v-else-if must be used after v-else-if or v-if (next to)

v-show is true to render the element, false is otherwise

The difference between the two

  • v-if: Regenerate or create elements every time
  • v-show: The rendered element is always saved in the DOM, just toggle the display:none style of the element

v-if Switching is expensive, v-show Initial rendering is expensive

————————————————– ————————————————– ——————————–

v-for directive

<template>
  <div id="app">
    <span>vue2-Test loop command</span><br/>
    <ul>
       <li v-for="(item, index) in arr" :key="index">
          {<!-- -->{ item }}
       </li>
    </ul>
  </div>
</template>

<script>
export default{
  name: "HomeView",
  data(){
    return{
     arr:[123,456,789]
    }
  }
 }
</script>


<style>
</style>

The webpage effect is as follows

3.Vue2 components

3.1 Parent component introduces child components

  • The parent component imports the child component
  • Register the child component component in the parent component: { childrenComponent }
  • Parent component uses child component

3.2 Parent component passes value to child component

Child components receive it through the props attribute

  • type: type of value-passed attribute
  • default: the default value when the parent component is not received
......

<script>
export default{
  props:{
    mes:{
        type:String,
        default:'Subcomponent default value',
    },
  },
  data(){
    return{
    }
  },
  methods:{

    }
  }
</script>

......

3.3 Sub-component passes value to parent component

Custom event emit pass value

—Subassembly

<template>
 <div>
    <button @click="transfor">Sub component transfers value button to parent component</button>
 </div>
</template>

<script>
export default{
  props:{

  },
  data(){
    return{
    }
  },
  methods:{
      transform(){
                   //The first parameter is the name of the custom event, and the second parameter is the data passed by the child to the parent.
        this.$emit('transforFather','Data passed by the child component to the parent component')
      }
    }
  }
</script>


<style>
</style>

—Parent component

<template>
  <div id="app">
    <span> {<!-- -->{title}}</span><br/>
    <Children @transforFather="jieshou"></Children>
  </div>
</template>

<script>
import Children from './components/Children.vue'
export default{
  data(){
    return{
      title:"vue2-Test the child to pass value to the parent"
    }
  },
  components:{
    Children
  },
  methods:{
    jieshou(value){
      this.title = value;
    }
  }
 }
</script>

<style>
</style>

—Page style

—Page style after clicking button event

4. Create Vue3 project

>>>npm init vite@latest (packaging method vite) —Volar plug-in (VS code)

Start Vue3 project command

>>>npm run dev

4.1Vue3 component structure

<template>
  <div id="app">
    {<!-- -->{title}}<br>
    <button @click="change">Vue3 click button event</button>
  </div>
</template>

<script setup>
//Define attributes
const title = "This is a Vue3 page"
//Define method
const change = ()=>{
  console.log(123)
}
</script>

<style>
</style>


4.2Vue3’s responsive variables

Interview question: Similarities and differences between ref and reactive

—>let title = ref(“This is a Vue3 page”)

—>let obj = reactive({
name:”zhiping”,
age:18,
phone:123
})

  • Same: ref and reactive are keywords used to define responsive variables
  • Difference: ref is generally used to define basic data types, but it can also define complex data types.
  • Reactive can generally only be used to define Objects, Arrays, etc. Reference data types
?
<template>
  <div id="app">
    {<!-- -->{title}}<br>
    <button @click="changeRef">ref click button event</button><br>
    name:{<!-- -->{ obj.name }}<br>
    age:{<!-- -->{ obj.age }}<br>
    phone:{<!-- -->{ obj.phone }}<br>
    <button @click="changeReactive">reactive click button event</button><br>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
//Define attributes
let title = ref("This is a Vue3 page")

let obj = reactive({
  name:"zhiping",
  age:18,
  phone:123
})
//Define method
const changeRef = ()=>{
 title.value = "The value of the responsive variable"
}
const changeReactive=() =>{
  obj.age = 123,
  obj.name = "xinyi",
  obj.phone = 456
}
</script>

<style>
</style>

Click the button and the page effect is as follows———————————————— ————————————————– ——

4.3 Arrow function of Vue3

Ordinary function function fn(){ }

Arrow function function fn = ()=>{ }

The difference between arrow functions and ordinary functions

1. Difference in writing

Arrow function: If there are no parameters, the parentheses cannot be omitted; if there is only one parameter, the parentheses can be omitted.

Ordinary function: If the function body has only one line, then {} (curly brackets) can be omitted, and retrun can be omitted.

2.this points to the difference

Arrow function: The this of the arrow function points to when defined, and the first this of the outer ordinary function

Ordinary function: this points to the outer first object

4.4Vue3 slot

The subcomponent Test.vue is as follows

—The label of the subcomponent uses the slot to be filled

The parent component App.vue is as follows

—Introduce child components into parent components and fill slots (Default filling)

—page

—Usage of named slots

The name binding slot’s scope

Can be abbreviated when binding a scope when filling a slot

Default v-slot — #default

Specific slot v-slot: xx — #xx

4.4Vue3 life cycle

  • Before creation (setup): beforeCreate(), created()
  • When rendering: beforeMount(), mounted()
  • When updating: beforeUpdate(), updated()
  • When destroyed: beforeUnmount(), unmounted()

beforeMount() function executed when the component is mounted to the node

mounted() is executed after the page starts rendering and can be used to initialize the page.

4.6Vue3 front-end and back-end connection

What is the same origin policy?

Protocol, domain name, port number Same — can receive requests

Cross-domain solutions

1. Configure cross-domain

1.1 Notes

@CrossOrigin

1.2 Global configuration

2. Reverse proxy

—Front-end configuration information

—Backend configuration file (application.properties)

  • server.port:XX (specific port number)
  • server.servlet.context-path=/api

————————————————– ———test—————————————- ————————–

The page effect is as follows—

Front-end code—

<template>
  <div id="">
    <button @click="get">get</button>
    <button @click="post">post</button>
  </div>
</template>

<script setup>
import axios from 'axios'
const get = () => {
  axios.get("http://localhost:8080/get").then((res)=>{
    console.log(res)
  })
}
const post = () => {
  axios.post("http://localhost:8080/post").then((res)=>{
    console.log(res)
  })
}
</script>

<style>
</style>

Backend code —

package com.example.demo.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaozhuang
 * @create 2023-11-08-21:45
 */
@RestController
@CrossOrigin
public class AxiosController {

    @GetMapping("/get")
    String get(){
        return "This is a get request";
    }

    @PostMapping("/post")
    String post(){
        return "This is a post request";
    }

}

Button click page effect

—The web page directly initiates a request

—The browser can only send get requests, cannot send post requests, otherwise an error will be reported as follows

The knowledge points of the article match the official knowledge archives, and you can further learn relevant knowledge. Vue entry skill treevue3 basics (JS)Vue3 life cycle function 39805 people are learning the system