[SRC · Tanwei /vue3.0_demo – Code Cloud – Open Source China (gitee.com)]

Vue3 pre –

01- Why learn VUE3

Objective: To understand the current status of VUE3, its advantages, and its future

Vue3 status:

  • Vue-next (Opens New Window) : VuE3.0 was officially released on September 18, 2020. However, due to the lack of ecosystem support surrounding the launch, most developers are sitting on the fence.

  • Now that the major component libraries have been released to support VUe3.0, other ecosystems are constantly improving, which is the trend.

    • Elemental-plus (Opens New Window) a desktop component library based on Vue 3.0
    • Vant (Opens New Window) Vant3.0, the front end team open source mobile component library
    • Ant-design-vue (Opens new Window)Ant Design Vue 2.0, developed by the community according to Ant Design

Vue3 advantages:

  • It is one of the most popular front-end frameworks in China and opens New Window to the public.
  • The performance is improved, and the running speed is about 1.5 times that of VUe2. X
  • Smaller, on-demand compilation volume is smaller than vue2. X
  • Type inference and better support for Ts (typescript) is also a trend
  • Advanced giving exposes lower-level apis and provides more advanced built-in components
  • ★ Composition API, can better organize logic, packaging logic, reuse logic

Vue3 outlook:

  • This is the trend and more and more enterprises will definitely upgrade to Vue3.0 in the future
  • Large projects, more and more large projects can use Vue3.0 due to Ts friendly

Summary: Why learn VUE3?

  • Adapt to the market, learn popular technology to improve their competitiveness, give yourself a raise.

02-Vite basic use

Goal: To understand what Vite is and to create a VUE project using Vite to learn about VUE3

Vite: A Labour of love for New Windows

  • It is a lighter (hot update fast, package build fast) scaffolding tool for VUE projects.
  • Compared to vue-CLI, it has very few plug-ins installed by default and requires additional configuration as the development process becomes more and more dependent.
  • So: we will use vuE3 syntax for simple learning, and we will still use VUE-CLI for future projects

Vite basic use:

  • Create a projectNPM init vite-app Project nameorYarn Create Viet-app Project name
  • Install dependenciesnpm ioryarn
  • Start the projectnpm run devoryarn dev

Summary: What is vite?

  • Using Vite to create a project learn vuE3 syntax, using VUE-CLI to create a project for formal development.

03- Creating a VUE application

Objective: To learn how to create vuE3 application instances

Basic steps:

  • Import createApp in main.js
  • Define app.vue components and import main.js
  • Use createApp to create an application instance based on the app. vue component
  • Mount the #app container to index.html

Landing Code:

App.vue

<template>
  <div class="container">I'm the root component</div>
</template>
<script>
export default {
  name: 'App'
}
</script>
Copy the code

main.js

// Create a vue application // 1. // create an application instance based on the root component // 4. / app.vue 'const app = createApp(app) import {createApp} from 'vue' import app from './ app.vue' const app = createApp(app) app.mount('#app')Copy the code

Summary: How do I create vUE application instances?

  • Create an application instance with createApp — extension functionality will be done in the app.

4- Option API and composition API

Goal: To understand what option API writing is and what combination API writing is.

What is the Options API

  • This is the option API notation we used in the Vue2. X project

    • Code style: data options write data, methods options write functions… , a functional logic of code dispersion.
  • Advantages: Easy to learn and use, the location of the code has been agreed

  • Disadvantages: poor code organization, similar logic code is not easy to reuse, logic complex code is not easy to read.

  • Add-on: Although mixins are provided to encapsulate logic, the probability of data function overwriting is high and difficult to maintain.

<template>
  <div class="container">
    <div>Mouse position:</div>
    <div>X轴:{{x}}</div>
    <div>Y轴:{{y}}</div>
    <hr>
    <div>{{count}} <button @click="add()">Since the increase</button></div>  
  </div>
</template>
<script>
export default {
  name: 'App',
  data () {
    return {
      x: 0.y: 0.count: 0}},mounted() {
    document.addEventListener('mousemove'.this.move)
  },
  methods: {
    move(e) {
      this.x = e.pageX
      this.y = e.pageY
    },
    add () {
        this.count++
    }    
  },
  destroyed() {
    document.removeEventListener('mousemove'.this.move)
  }
}
</script>
Copy the code

What is the Compositon API

  • We will use composite API writing in the VUe3.0 project

    • Code style: A functional logic of code organized together (including data, functions…)
  • Advantages: When the function logic is complex and various, the function logic code is organized together for easy reading and maintenance

  • Disadvantages: Need good code organization ability and splitting logic ability, PS: everyone no problem.

  • Note: In order to facilitate the transition to vue3.0, the vue2.x option API is also supported

<template>
  <div class="container">
    <div>Mouse position:</div>
    <div>X轴:{{x}}</div>
    <div>Y轴:{{y}}</div>
    <hr>
    <div>{{count}} <button @click="add()">Since the increase</button></div>  
  </div>
</template>
<script>
import { onMounted, onUnmounted, reactive, ref, toRefs } from 'vue'
export default {
  name: 'App',
  setup () {
    // Mouse movement logic
    const mouse = reactive({
      x: 0.y: 0
    })
    const move = e= > {
      mouse.x = e.pageX
      mouse.y = e.pageY
    }
    onMounted(() = >{
      document.addEventListener('mousemove',move)
    })
    onUnmounted(() = >{
      document.removeEventListener('mousemove',move)
    })

    // add logic
    const count = ref(0)
    const add = () = > {
      count.value ++ 
    }

    // Return data
    return {
      ...toRefs(mouse),
      count,
      add
    }
  }
}
</script>
Copy the code

Conclusion:

  • Knowing the difference between option and composition apis, I recommend that you use composition apis in vue3.0 projects.

05- Combine apI-setup functions

Objective: To master the basic use of setup functions

Usage details:

  • setupIs a new component option that serves as a starting point for using composite apis in components.
  • From a component lifecycle perspective, it executes before the component instance is createdBeforeCreate vue2. XThe execution.
  • This means that in thesetupIn the functionthisNot yet a component instance,thisAt this point isundefined
  • The data and functions that need to be used in the template need to be in thesetupTo return.

Demo code:

<template>
  <div class="container">
    <h1 @click="say()">{{msg}}</h1>
  </div>
</template>
<script>
export default {
  setup () {
    console.log('Setup executes')
    console.log(this)
    // Define data and functions
    const msg = 'hi vue3'
    const say = () = > {
      console.log(msg)
    }

    return { msg , say}
  },
  beforeCreate() {
    console.log('beforeCreate executed ')
    console.log(this)}}</script>
Copy the code

Summary: The Setup component is executed before initialization and returns data and functions that can be used in the template.

06- Composition API- Life cycle

Objective: To master the lifecycle hook functions written using the composite API

Review the vue2. X lifecycle hook functions:

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

Recognize vue3.0 lifecycle hook functions

  • setupBefore creating an instance
  • onBeforeMountMount the DOM
  • onMountedMount after the DOM
  • onBeforeUpdateBefore updating components
  • onUpdatedAfter updating components
  • onBeforeUnmountBefore unloading and destruction
  • onUnmountedAfter unloading and destruction

Demo code:

<template>
  <div class="container">
    container
  </div>
</template>
<script>
import { onBeforeMount, onMounted } from 'vue'
export default {
  setup () {
    onBeforeMount(() = >{
      console.log('Before DOM rendering'.document.querySelector('.container'))
    })
    onMounted(() = >{
      console.log('1 after DOM rendering'.document.querySelector('.container'))
    })
    onMounted(() = >{
      console.log('DOM rendered 2'.document.querySelector('.container'))}}}</script>
Copy the code

Summary: The composite API has seven lifecycle hooks that can be used multiple times in the same order of execution and writing.

07- Combine apI-reactive functions

Objective: To master defining reactive data using reactive functions

Define reactive data:

  • Reactive is a function that defines a complex data type as reactive data.

Demo code:

<template>
  <div class="container">
    <div>{{obj.name}}</div>
    <div>{{obj.age}}</div>
    <button @click="updateName">Modify the data</button>
  </div>
</template>
<script>
import { reactive } from 'vue'
export default {
  name: 'App',
  setup () {
    // Common data
    // const obj = {
    // name: 'ls',
    // age: 18
    // }
    const obj = reactive({
      name: 'ls'.age: 18
    })

    // Change the name
    const updateName = () = > {
      console.log('updateName')
      obj.name = 'zs'
    }

    return { obj ,updateName}
  }
}
</script>
Copy the code

Summary: Usually used to define reactive object data

08- Combined API-toref functions

Objective: To use the toRef function to convert a property of a responsive object into a single responsive data with associated values.

Define reactive data:

  • ToRef is a function that converts a property of a responsive object into a single responsive data with associated values.

Demo code:

<template>
  <div class="container">
    {{name}} <button @click="updateName">Modify the data</button>
  </div>
</template>
<script>
import { reactive, toRef } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. Reactive data objects
    const obj = reactive({
      name: 'ls'.age: 10
    })
    console.log(obj)
    // 2. Use only the name data in the template
    // Note: Attribute data deconstructed from a reactive data object is no longer reactive data
    // let {name} = obj
    const name = toRef(obj, 'name')
    // console.log(name)
    const updateName = () = > {
      console.log('updateName')
      // toRef converts responsive data into objects, and value stores the location of the value
      name.value = 'zs'
    }

    return {name, updateName}
  }
}
</script>
<style scoped lang="less"></style>
Copy the code

Usage scenario: There is a reactive object data, but only one of the data is needed in the template

09- Combine API-Torefs functions

Goal: to master the use toRefs function definition transform the response of all properties in response to a data type, is often used to deconstruct | reactive defined object.

Define reactive data:

  • ToRefs is a function that converts all properties of a reactive object into individual reactive data, making the object ordinary, and the values associated

Demo code:

<template>
  <div class="container">
    <div>{{name}}</div>
    <div>{{age}}</div>
    <button @click="updateName">Modify the data</button>
  </div>
</template>
<script>
import { reactive, toRef, toRefs } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. Reactive data objects
    const obj = reactive({
      name: 'ls'.age: 10
    })
    console.log(obj)
    // 2. Deconstruct or expand reactive data objects
    // const {name,age} = obj
    // console.log(name,age)
    // const obj2 = {... obj}
    // console.log(obj2)
    // As a result, the data is not responsive
    const obj3 = toRefs(obj)
    console.log(obj3)

    const updateName = () = > {
      // obj3.name.value = 'zs'
      obj.name = 'zs'
    }

    return{... obj3, updateName} } }</script>
<style scoped lang="less"></style>
Copy the code

Deconstruction | usage scenarios: stripping response type object (a), want to use several or all of the properties of reactive object response data.

10- Combined API-ref functions

Objective: To define reactive data using the REF function, generally for simple types of data

Define reactive data:

  • The ref function, often used for simple data types defined as reactive data

    • And then you modify the value, and when you get the value, you need dot value
    • The.value can be omitted if ref is used to declare reactive data in the template

Demo code:

<template>
  <div class="container">
    <div>{{name}}</div>
    <div>{{age}}</div>
    <button @click="updateName">Modify the data</button>
  </div>
</template>
<script>
import { ref } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. name data
    const name = ref('ls')
    console.log(name)
    const updateName = () = > {
      name.value = 'zs'
    }
    // 2. age data
    const age = ref(10)

    // ref is used to define reactive data of simple data types
    // It is also possible to define reactive data of complex data types
    // Ref is most applicable when the data is not available
    // const data = ref(null)
    // setTimeout(()=>{
    // data.value = res.data
    / /}, 1000)

    return {name, age, updateName}
  }
}
</script>
Copy the code

Usage Scenarios:

  • When you know exactly what you want is a responsive dataobjectSo you can use Reactive
  • In other cases use ref

11- Knowledge application cases

Goal: Use what you have learned to complete a composite API instance

Basic steps:

  • Recording mouse coordinates

    • Define a reactive data object containing x and Y attributes.
    • Listen for the document mouse movement event after the component is rendered
    • Specify the move function as the event-corresponding method, and modify the coordinates in the function
    • Used in the setup return data template
  • Add one function

    • Define reactive data of a simple data type
    • Define a method to modify a number
    • Used in setup return data and functions, templates

Drop code:

<template>
  <div class="container">
    <div>coordinates</div>
    <div>x: {{x}}</div>
    <div>y: {{y}}</div>
    <hr>
    <div>{{count}} <button @click="add">Accumulative 1</button></div>
  </div>
</template>
<script>
import { onMounted, onUnmounted, reactive , ref, toRefs} from 'vue'
const useMouse = () = > {
    1. Record the mouse coordinates
    // 1.1 declares a response data, which is an object containing x and y
    const mouse = reactive({
      x: 0.y: 0
    })
    // 1.3 Modify responsive data
    const move = (e) = > {
      mouse.x = e.pageX
      mouse.y = e.pageY
    }
    // Wait for dom 1.2 to render. Listen for events
    onMounted(() = >{
      document.addEventListener('mousemove', move)
    })
    // 1.4 Component consumption, delete event
    onUnmounted(() = >{
      document.removeEventListener('mousemove', move)
    })

    return mouse
}
export default {
  name: 'App',
  setup () {

    const mouse = useMouse()

    // 2
    const count = ref(0) 
    const add = () = > {
      count.value ++
    }



    return { ...toRefs(mouse), count, add }
  }
}
</script>
<style scoped lang="less"></style>
Copy the code

Summary: Experience writing composition apis and try to organize readable code.

12- Combined API-computed functions

Goal: To be able to define computed properties using computed functions

Define computed properties:

  • Computed functions are used to define computed properties, which cannot be modified.

Basic use:

<template>
  <div class="container">
    <div>This year: {{age}}</div>
    <div>Year after: {{newAge}} years</div>
  </div>
</template>
<script>
import { computed, ref } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. Calculate attributes: When you need to rely on existing responsive data, follow some logic to get a new data.
    const age = ref(16)
    // Get the age of the next year
    const newAge = computed(() = >{
      // The return value of this function is the value of the calculated property
      return age.value + 2
    })

    return {age, newAge}
  }
}
</script>
Copy the code

Advanced usage:

<template>
  <div class="container">
    <div>This year: {{age}}</div>
    <div>Year after: {{newAge}} years</div>
    <! -- Calculate attributes with v-model binding -->
    <input type="text" v-model="newAge">
  </div>
</template>
<script>
import { computed, ref } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. Calculate attributes: When you need to rely on existing responsive data, follow some logic to get a new data.
    const age = ref(16)
    // Get the age of the next year
    // const newAge = computed(()=>{
    // // The return value of this function is the value of the calculated property
    // return age.value + 2
    // })

    // Compute attributes for advanced use, pass object
    const newAge = computed({
      // get gets the value of the calculated property
      get(){
        return age.value + 2
      },
      // The set function is triggered when you set the value of the calculated property
      set (value) {
        age.value = value - 2}})return {age, newAge}
  }
}
</script>
Copy the code

Purpose: To enable bidirectional data binding for computed properties.

Summary: Calculate two uses of attributes

  • For a computed function, the return value is the value of the computed property
  • For a computed incoming object, GET gets the value of a computed property, and set listens for computed property changes.

13- Combine apI-watch functions

Objective: To define listeners using the watch function

Define computed properties:

  • The watch function is used to define listeners

Listen for reactive data defined by ref

Listen for multiple reactive data data

Listen for reactive data defined by Reactive

Listen to reactive data defined by Reactive, a particular property

The depth of the listening

The default implementation

<template>
  <div class="container">
    <div>
      <p>Count: {{count}}</p>
      <button @click="add">To change the data</button>
    </div>
    <hr>
    <div>
      <p>{{obj.name}}</p>
      <p>{{obj.age}}</p>
      <p>{{obj.brand.name}}</p>
      <button @click="updateName">Change a name</button>
      <button @click="updateBrandName">Change the brand name</button>
    </div>
  </div>
</template>
<script>
import { reactive, ref, watch } from 'vue'
export default {
  name: 'App',
  setup () {
    const count = ref(0)
    const add = () = > {
      count.value++
    }
    // You can use watch when you need to monitor data changes
    // 1. Listen on a ref
    The first parameter is the target to listen on
    // 1.2 Function triggered when the second argument changes
    // watch(count, (newVal,oldVal)=>{
    // console.log(newVal,oldVal)
    // })


    const obj = reactive({
      name: 'ls'.age: 10.brand: {
        id: 1.name: 'BMW'}})const updateName = () = > {
      obj.name = 'zs'
    }
    const updateBrandName = () = > {
      obj.brand.name = 'Mercedes'
    }
    // 2. Monitor a reactive data
    watch(obj, () = >{
      console.log('The data has changed')
    })

    watch(() = >obj.brand, () = >{
      console.log('Brand data has changed')
    },{
      // 5. Deep listening is required
      deep: true.// 6. Want to trigger by default
      immediate: true
    })

    // 3. Monitor multiple data changes
    // watch([count, obj], ()=>{
    // console.log(' Listening for multiple data changes ')
    // }) 


    // 4. Listen for the change of a property in the object, for example, obj.name
    // We need to write a function to return this property in order to listen
    // watch(()=>obj.name,()=>{
    // console.log(' Listen to obj.name changed ')
    // })

    return {count, add, obj, updateName, updateBrandName}
  }
}
</script>
Copy the code

Summary: Master the various usages of watch.

Deep listening demo

14- Combines apI-ref attributes

Goal: Learn how to bind DOM or components using the REF attribute

To obtain a DOM or component instance, you can use the ref attribute, which is separate from vue2.0

Get a single DOM or component

<template>
  <div class="container">
    <! -- Vue2.0 gets a single element -->
    <! -- 1. Bind the element with the ref attribute -->
    <! $this.$refs.box -->
    <! <div ref="box">
    <! -- Vue2.0 get multiple elements for traversal -->
    <! -- 1. The element to be traversed by the ref attribute binding -->
    <! $this.$refs.li -->
    <! -- <ul> <li v-for="i in 4" :key="i" ref="li">{{i}}</li> </ul> -->

    <! -- Single element -->
    <div ref="dom">I am a box</div>
    <! -- Iterated elements -->
    <ul>
      <li v-for="i in 4" :key="i" :ref="setDom">The first LI {{I}}</li>
    </ul>
  </div>
</template>
<script>
import { onMounted, ref } from 'vue'
export default {
  name: 'App',
  setup () {
    // 1. Get a single element
    // 1.1 defines an empty response data as defined by ref
    If you want to retrieve the DOM element, bind it to the element using the ref attribute.
    const dom = ref(null)
    onMounted(() = >{
       console.log(dom.value)
    })
  }
}
</script>
<style scoped lang="less"></style>
Copy the code

Gets the DOM or component that v-for traverses

    // 2. Get the element traversed by v-for
    // 2.1 defines an empty array to receive all LI's
    // 2.2 Define a function to push the DOM into an empty array
    const domList = []
    const setDom = (el) = > {
      domList.push(el)
    }
    onMounted(() = >{
      console.log(domList)
    })
    return {dom, setDom}
Copy the code

Conclusion:

  • Single element: declare the ref response data, return it to the template, bind the data by ref
  • Iterated elements: define an empty array, assign a function to fetch the elements, return them to the template, and bind the function with ref

15- Composite API- Parent-child communication

Goal: Master parent-child component communication using the props and emits options

Father the son:

<template>
  <div class="container">
    <h1>The parent component</h1>
    <p>{{money}}</p>
    <hr>
    <Son :money="money" />
  </div>
</template>
<script>
import { ref } from 'vue'
import Son from './Son.vue'
export default {
  name: 'App'.components: {
    Son
  },
  // The parent component's data is passed to the child component
  setup () {
    const money = ref(100)
    return { money }
  }
}
</script>
Copy the code
<template>
  <div class="container">
    <h1>Child components</h1>
    <p>{{money}}</p>
  </div>
</template>
<script>
import { onMounted } from 'vue'
export default {
  name: 'Son'.// The child component can use props to receive data from the parent component
  props: {
    money: {
      type: Number.default: 0
    }
  },
  setup (props) {
    // Get the parent component data money
    console.log(props.money)
  }
}
</script>
Copy the code

Child the parent:

<template>
  <div class="container">
    <h1>The parent component</h1>
    <p>{{money}}</p>
    <hr>
+    <Son :money="money" @change-money="updateMoney" />
  </div>
</template>
<script>
import { ref } from 'vue'
import Son from './Son.vue'
export default {
  name: 'App'.components: {
    Son
  },
  // The parent component's data is passed to the child component
  setup () {
    const money = ref(100)
+    const updateMoney = (newMoney) = > {
+      money.value = newMoney
+    }
+    return { money , updateMoney}
  }
}
</script>
Copy the code
<template>
  <div class="container">
    <h1>Child components</h1>
    <p>{{money}}</p>
+    <button @click="changeMoney">Spend 50 yuan</button>
  </div>
</template>
<script>
import { onMounted } from 'vue'
export default {
  name: 'Son'.// The child component can use props to receive data from the parent component
  props: {
    money: {
      type: Number.default: 0}},// props parent component data
  // emit a function that fires custom events
+  setup (props, {emit}) {
    // Get the parent component data money
    console.log(props.money)
    // Pass the value to the parent component
+    const changeMoney = () = > {
      // It's 50 yuan
      // Tell the parent that money needs to become 50
+      emit('change-money'.50) + +}return {changeMoney}
  }
}
</script>
Copy the code

Extension:

  • At the time of vue2 2.x.syncAnother way to implement two-way data binding is to remove the V-Model
<! -- <Son :money='money' @update:money="fn" /> -->Abbreviations:<Son :money.sync='money'  />
Copy the code
  • As of Vue3.0, usev-model:money="money"Can be
    <! -- <Son :money="money" @update:money="updateMoney" /> -->
    <Son v-model:money="money" />
Copy the code

Conclusion:

  • Parent to child: Use props data in setupSetup (props){// props is parent component data}
  • Emit from child to parent: Emit from custom event when emittedSetup (props,{emit}){// emit is the trigger function}
  • In vue3.0v-model 和 .syncHave merged intov-modelinstruction

16- Composite API- Dependency injection

Objective: Learn to use provide function and Inject function to complete data communication of descendant components

Usage scenario: There is a parent component, in which there are children components, there are children components, there are many children components, share the parent component data.

Demo code:

<template>
  <div class="container">
    <h1>The parent component {{money}}<button @click="money=1000">To send money</button></h1>
    <hr>
    <Son />
  </div>
</template>
<script>
import { provide, ref } from 'vue'
import Son from './Son.vue'
export default {
  name: 'App'.components: {
    Son
  },
  setup () {
    const money = ref(100)
    const changeMoney = (saleMoney) = > {
      console.log('changeMoney',saleMoney)
      money.value = money.value - saleMoney
    }
    // Provide the data to descendant components provide
    provide('money', money)
    // Provide the function to the descendant component provide
    provide('changeMoney', changeMoney)

    return { money }
  }
}
</script>
<style scoped lang="less"></style>
Copy the code
<template>
  <div class="container">
    <h2>Subcomponents {{money}}</h2>
    <hr>
    <GrandSon />
  </div>
</template>
<script>
import { inject } from 'vue'
import GrandSon from './GrandSon.vue'
export default {
  name: 'Son'.components: {
    GrandSon
  },
  setup () {
    // Receive data provided by the ancestor component
    const money = inject('money')
    return { money }
  }
}
</script>
<style scoped lang="less"></style>
Copy the code
<template>
  <div class="container">
    <h3>Sun component {{money}}<button @click="fn">Spending 20</button></h3>
  </div>
</template>
<script>
import { inject } from 'vue'
export default {
  name: 'GrandSon',
  setup () {
    const money = inject('money')
    // Sun component, spend 50, notify parent component app. vue component, modify
    // Can not modify the data, follow the radio data flow principle, plain speaking: the data is defined by the modification
    const changeMoney = inject('changeMoney')
    const fn = () = > {
      changeMoney(20)}return {money, fn}
  }
}
</script>
<style scoped lang="less"></style>
Copy the code

Conclusion:

  • Provide functions provide data and functions for future generations of components to use
  • The inject function injects data and functions provided by provide into the current component

17- Supplementary – V-model grammar sugar

Objective: To master the principle of V-Model syntax sugar of VUe3.0

Demo code:

<template>
  <div class="container">
    <! If you want to get a native event event object -->
    <! Fn (e){// e is the event object} -->
    <! $event = $event; $event = $event;
    <h1 @click="$event.target.style.color='red'">The parent component {{count}}</h1>
    <hr>
    <! If you want to get custom events -->
    <! Fn fn(data){// data fires custom event parameters} -->
    <! $event () {$event ();
    <! -- <Son :modelValue="count" @update:modelValue="count=$event" /> -->
    <Son v-model="count" />
  </div>
</template>
<script>
import { ref } from 'vue'
import Son from './Son.vue'
export default {
  name: 'App'.components: {
    Son
  },
  setup () {
    const count = ref(10)
    return { count }
  }
}
</script>
Copy the code
<template>
  <div class="container">
    <h2>Subcomponents {{modelValue}}<button @click="fn">Change the data</button></h2>
  </div>
</template>
<script>
export default {
  name: 'Son'.props: {
    modelValue: {
      type: Number.default: 0
    }
  },
  setup (props, {emit}) {
    const fn = () = > {
      // Change the data
      emit('update:modelValue'.100)}return { fn }
  }
}
</script>
Copy the code

Summary: When vue3.0 package components support V-Model, parent :modelValue child :modelValue @update:modelValue

Supplement: Vue2.0’s XXX. Sync syntax sugar parsing parent to child: XXX Child to parent @update: XXX In Vue3.0 uses V-model: XXX instead.

18- Supplementary – Mixins syntax

Objective: To master the basic usage of mixins syntax, the way vue2.x encapsulates logic, and vue3.0 recommends using composite apis

Official words:

  • Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain any component option. When a component uses mixin, all mixin options are “blended” into the component’s own options.

Understand global interfuse: All components interfuse this logic code

Global mixin code:

// 全局混入 全局mixin
// Vue 2.0 writing vue. mixin({})
app.mixin({
  methods: {
    say () {
      console.log(this.$el,Call say in Mounted)
    }
  },
  mounted () {
    this.say()
  }
})
Copy the code
<template>
  <div class="container1">
    <h1>Author: Jay Chou<a href="javascript:;">Focus on</a> </h1>
    <hr>
    <Son />
  </div>
</template>
<script>
import Son from './Son.vue'
export default {
  name: 'App'.components: {
    Son
  }
}
</script>
Copy the code
<template>
  <div class="container2">
    <h2>Author: Jay Chou<button>Focus on</button> </h2>
  </div>
</template>
<script>
export default {
  name: 'Son'
}
</script>
<style scoped lang="less"></style>
Copy the code

Global blending images:

Understand local blending: Blending through the mixins option

// Configure objects
export const followMixin =  {
  data () {
    return {
      loading: false}},methods: {
    followFn () {
      this.loading = true
      // simulate the request
      setTimeout(() = >{
        // Omit the request code
        this.loading = false
      },2000)}}}Copy the code
<template>
  <div class="container1">
    <h1>Author: Jay Chou<a href="javascript:;" @click="followFn">{{loading? 'In the request... ':' focus'}}</a> </h1>
    <hr>
    <Son />
  </div>
</template>
<script>
import Son from './Son.vue'
import {followMixin} from './mixins'
export default {
  name: 'App'.components: {
    Son
  },
  mixins: [followMixin]
}
</script>
Copy the code
<template>
  <div class="container2">
    <h2>Author: Jay Chou<button @click="followFn">{{loading? 'loading... ':' focus'}}</button> </h2>
  </div>
</template>
<script>
import {followMixin} from './mixins'
export default {
  name: 'Son'.mixins: [followMixin]
}
</script>
<style scoped lang="less"></style>
Copy the code

Summary: In Vue2.0, some reusable logic can be encapsulated using mixins, while logic code conflicts need to be considered. Vue3.0’s composite API solves this problem so well that mixins are no longer recommended.

Local mixing code:

Summary of mind mapping: