vue3.0 from getting started to getting into the ground -- Review components under advanced

Posted by scrupul0us on Tue, 01 Feb 2022 10:45:30 +0100

catalogue

ref reference

Dynamic component

Slot

Custom instruction

Table case

summary

ref reference

1. What is ref reference

ref is used to assist developers in Without relying on jQuery , get the reference of DOM element or component.
Each vue component instance contains a $refs object , which stores the reference of the corresponding DOM element or component. By default, Component's $refs points to an empty object .

 2. Using ref to reference DOM elements

If you want to use ref to reference DOM elements on a page, you can do so as follows:

 4. Controls the on-demand switching of text boxes and buttons

The Boolean inputVisible is used to control the on-demand switching between text box and button in the component. The example code is as follows:

 5. Let the text box get focus automatically

When the text box is displayed, if you want it to get focus immediately, you can add a ref reference to it and call the function of the native DOM object .focus() Method is enough. The example code is as follows:

 6. this.$nextTick(cb) method

Component $nextTick(cb) Method, which will call back cb Postpone execution until after the next DOM update cycle . The popular understanding is that after the dom of the component is asynchronously re rendered, the cb callback function is executed. This ensures that the cb callback function can operate on the latest DOM elements.

Dynamic component

Dynamic components refer to Dynamically switch the display and hiding of components . vue provides a built-in <component> Component, which is specially used to realize the dynamic rendering of components.
  • ① < component > is a placeholder for a component
  • ② Dynamically specify the name of the component to render through the is attribute
  • ③ < component is = "name of component to render" > < / component

2. How to realize dynamic component rendering

 

3. Keep alive

By default, when switching dynamic components The state of the component cannot be maintained . At this point, you can use vue's built-in <keep-alive> Components maintain the state of dynamic components. The example code is as follows:

Slot

1. What is a slot

slot ( Slot )Yes vue for Packager of component Ability to provide. Allow developers to package components equivocal , The part you want to be specified by the user It is defined as a slot, which can be regarded as reserved for users during component packaging Placeholder for content

 2. Experience the basic usage of slots

When encapsulating components, slots can be defined through the < slot > element to reserve content placeholders for users. The example code is as follows:

2.1 No reserved slots Your content will be discarded

If no < slot > slots are reserved when packaging components, any customized content provided by the user will be discarded.

2.2 backup content

When encapsulating components, you can provide for reserved < slot > slots Backup content (default content). If the user of the component does not provide any content for the slot, the backup content will take effect. The example code is as follows:

 3. Named slot

If when packaging components Multiple slot nodes need to be reserved , you need to specify for each < slot > slot Specific name . such Slot with specific name It's called a named slot. The example code is as follows:
Note: if the slot name is not specified, there will be an implied name called“ default ".

3.1 providing content for named slots

When providing content to named slots, we can <template> Use on element v-slot Instruction and provide its name as a parameter of v-slot. The example code is as follows

3.2 abbreviated form of named slot

Like v-on and v-bind, v-slot also has abbreviations, that is, everything before the parameter( v-slot: )Replace with characters # . for example v-slot: The header can be rewritten as # header

 4. Scope slot

In the process of packaging components, props data can be bound for reserved < slot > slots < slot > with props data Called“ Scope slot ”. The example code is as follows:

4.1 deconstruct the Prop of the scope slot

For the data objects provided by the scope slot, deconstruction assignment can be used to simplify the data receiving process. The example code is as follows:

4.2 declaring scope slots

In the process of encapsulating MyTable components, you can Scope slot Pass the data of each row of the table to the user of the component.

4.3 using scope slots

When using the MyTable component, customize the rendering method of cells and receive the data provided by the scope slot

Custom instruction

1. What is a custom instruction

vue officially provides v-for, v-model, v-if and other commonly used built-in instructions. In addition, vue also allows developers to customize instructions

The user-defined instructions in vue are divided into two categories: private user-defined instructions and global user-defined instructions

2. Syntax for declaring private custom instructions

In each vue component, private user-defined instructions can be declared under the directives node. The example code is as follows:

 3. Use custom directives

When using custom instructions, you need to add a v-prefix. The example code is as follows:

 4. Syntax for declaring global custom directives

Custom instructions for global sharing need to be declared through "instance object of single page application". The example code is as follows:

 5. updated function

The mounted function is only called when the element is inserted into the DOM for the first time. The mounted function will not be triggered when the DOM is updated. The updated function is called after each DOM update. The example code is as follows:

Note: when using custom instructions in vue2 projects, [mounted - > bind] [Updated - > update]

 6. Function abbreviation

If the format of the updated function is exactly the same as that of the updated function:

 7. Parameter value of instruction

When Binding instructions, you can“ Equal sign ”The form of is instruction binding Specific parameter values , the example code is as follows:

 

Table case

1. Case effect

 2. Knowledge points used

  • Component encapsulation
  • Named slot
  • Scope slot
  • Custom instruction

3. Implementation steps

1. Build the basic structure of the project

1.1 initialization items

1. Run the following command on the terminal to initialize the vite project:

2. cd to the project root directory and install dependencies:

3. Install less dependency package:

4. Open the project with vscode, and run the following command under the vscode integrated terminal to run the project:

npm init vite-app table-demo 
npm install 
npm i less -D
npm run dev 
1.2 Sort out the project structure
Reset App.vue Code structure of root component:
<template>
 <div>
 <h1>App Root component</h1>
 </div>
</template> <script>
export default {
 name: 'MyApp', }
</script> <style lang="less" scoped></style>
2. Delete components Directory HelloWorld.vue assembly
3. Reset index.css Styles in:
:root {
 font-size: 12px; }
body {
 padding: 8px; } 1234567
4. Put the information Directory css Copy and paste folders to assets Directory, and in main.js In the entry file
Import bootstrap.css :
import { createApp } from 'vue'
import App from './App.vue'
// Import bootstrap style sheet
import './assets/css/bootstrap.css'
import './index.css'
createApp(App).mount('#app')
2. Request data for item list
npm install axios@0.21.0 -S
2. In main.js In the entry module, import and global configuration axios :
/ 1. Import axios
import axios from 'axios'
const app = createApp(App)
// 2. Mount axios to the global. In the future, each component can be directly accessed through
this.$http replace axios launch Ajax request
app.config.globalProperties.$http = axios
// 3. Configure the root path of the request
axios.defaults.baseURL = 'https://www.escook.cn'
app.mount('#app')
3. In App.vue Component data Statement in goodslist Item list data:
data() {
 return {
 // Item list data
 goodslist: []
 }
} 
4. In App.vue Component methods Statement in getGoodsList Method to request the data of the product list from the server:
methods: {
 // Initialize the data of the item list
 async getGoodsList() {
 // Initiate an Ajax request
 const { data: res } = await this.$http.get('/api/goods')
 // request was aborted
 if (res.status !== 0) return console.log('Get product list missing
 Defeat!')
 // Request succeeded
 this.goodslist = res.data
 }
}
5. stay App.vue Component, declare created Lifecycle function and call getGoodsList method:
created() {
 this.getGoodsList()
} 
3. encapsulation MyTable assembly
3.0 MyTable Packaging requirements of components
  • 1. The user passes the prop attribute named data to mytable The Vue component specifies the data source
  • 2. On mytable In the Vue component, a named slot named header is reserved
  • 3. On mytable In the Vue component, a scope slot with the name of body is reserved

3.1 create and use MyTable component

1. In components/my-table New under directory MyTable.vue assembly
<template>
 <div>MyTable assembly</div>
</template> <script>
export default {
 name: 'MyTable',
}
</script> <style lang="less" scoped></style>
stay App.vue Import and register in component MyTable.vue Components:
/ Import MyTable assembly
import MyTable from './components/my-table/MyTable.vue'
export default {
 name: 'MyApp',
 // ...  Omit other codes
 // Register MyTable component
 components: {
 MyTable
 }
} 
3. stay App.vue Component DOM Used in structure MyTable.vue Components:
<template>
 <div>
 <h1>App Root component</h1>
 <hr />
 <!-- Using table components -->
 <my-table></my-table>
 </div>
</template> 
3.2 Declare for form data data source
1. stay MyTable.vue Component props The name of the table declared in the node data data source
export default {
 name: 'MyTable',
 props: {
 // Table data source
 data: {
 type: Array,
 required: true,
 default: [],
 },
 },
} 
2. stay App.vue Used in components MyTable.vue Components, through Form of property binding Specify for table data Data source:
<!-- Using table components -->
<my-table :data="goodslist"></my-table> 
3.3 encapsulation MyTable Template structure of component
1. Based on bootstrap The Tables provided are in MyTable.vue Render the most basic template structure in the component
( https://v4.bootcss.com/docs/content/tables/ ) ,
<template>
 <table class="table table-bordered table-striped">
 <!-- Header area of the table -->
 <thead>
 <tr>
 <th>#</th>
 <th>Trade name</th>
 <th>Price</th>
 <th>label</th>
 <th>operation</th>
 </tr>
 </thead>
 <!-- Body area of the table -->
 <tbody></tbody>
 </table>
</template>
2. In order to improve the reusability of components, it is best to put the table Title Area Reserved as <slot> Named slot It is convenient for users to customize the title of the table
<template>
 <table class="table table-bordered table-striped">
 <!-- Header area of the table -->
 <thead>
 <tr>
 <!-- Named slot -->
 <slot name="header"></slot>
 </tr>
 </thead>
 <!-- Body area of the table -->
 <tbody></tbody>
 </table>
</template> 
3. stay App.vue Component, through Named slot In the form of MyTable.vue Specify a title name for the component:
<!-- Using table components -->
<my-table :data="goodslist">
 <!-- Table title -->
 <template v-slot:header>
 <th>#</th>
 <th>Trade name</th>
 <th>Price</th>
 <th>label</th>
 <th>operation</th>
 </template>
</my-table>
3.4 Reserved name is body Scope slot for
1. stay MyTable.vue Component, through v-for The command loops through the data rows of the table:
<template>
 <table class="table table-bordered table-striped">
 <thead>
 <tr>
 <slot name="header"></slot>
 </tr>
 </thead>
 <!-- Body area of the table -->
 <tbody>
<!-- use v-for Instruction to cycle through the data rows of the table -->
 <tr v-for="(item, index) in data" :key="item.id"></tr>
 </tbody>
 </table>
</template>
In order to improve MyTable.vue For the reusability of components, it is best to put the data in the table data row td Cell reserved as <slot> Named slot. The example code is as follows:
<template>
 <table class="table table-bordered table-striped">
 <thead>
 <tr>
 <slot name="header"></slot>
 </tr>
 </thead>
 <!-- Body area of the table -->
 <tbody>
 <!-- use v-for Instruction to cycle through the data rows of the table -->
 <tr v-for="(item, index) in data" :key="item.id">
 <!-- For data rows td Reserved slot -->
 <slot name="body"></slot>
 </tr>
 </tbody>
 </table>
</template> 
3. In order for the user of the component to provide body When the content of the slot can be customized, the rendering method of the content needs to be
body Named slot Upgrade to Scope slot
<template>
 <table class="table table-bordered table-striped">
 <thead>
 <tr>
 <slot name="header"></slot>
 </tr>
 </thead>
 <!-- Body area of the table -->
 <tbody>
 <!-- use v-for Instruction to cycle through the data rows of the table -->
 <tr v-for="(item, index) in data" :key="item.id">
 <!-- For data rows td Reserved scope slot -->
 <slot name="body" :row="item" :index="index"></slot>
 </tr>
</tbody>
 </table>
</template>
4. stay App.vue Component, based on Scope slot Render table data in the following way:
<!-- Using table components -->
<my-table :data="goodslist">
 <!-- Table title -->
 <template v-slot:header>
 <th>#</th>
 <th>Trade name</th>
 <th>Price</th>
 <th>label</th>
 <th>operation</th>
 </template>
 <!-- Cells in each row of the table -->
 <template v-slot:body="{ row, index }">
 <td>{{ index + 1 }}</td>
 <td>{{ row.goods_name }}</td>
 <td>¥{{ row.goods_price }}</td>
 <td>{{ row.tags }}</td>
 <td>
 <button type="button" class="btn btn-danger btn-sm">delete
</button>
 </td>
 </template>
</my-table> 
4. Implement deletion function
1. Bind for delete button click Event handler:
<td>
 <button type="button" class="btn btn-danger btn-sm"
@click="onRemove(row.id)">delete</button>
</td> 123
stay App.vue Component methods The event handling functions declared in are as follows:
methods: {
 // Delete product information according to Id
 onRemove(id) {
 this.goodslist = this.goodslist.filter(x => x.id !== id)
 },
}
5. Realize the function of adding labels
5.1 custom render label columns
according to bootstrap Provided Badge effect, the label information of the circular rendering commodity is as follows:
( https://v4.bootcss.com/docs/components/badge/#contextual-variations )
<td>
 <span class="badge badge-warning ml-2" v-for="item in row.tags"
:key="item">{{tag}}</span>
</td> 
5.2 realization input and button On demand display of
use v-if combination v-else Command, control input and button On demand display of:
<td>
 <!-- Based on the current row inputVisible,To control input and button On demand Exhibition
 show-->
 <input type="text" class="form-control form-control-sm ipt-tag"
v-if="row.inputVisible">
 <button type="button" class="btn btn-primary btn-sm" velse>+Tag</button>
 <span class="badge badge-warning ml-2" v-for="item in row.tags"
:key="item">{{item}}</span>
</td> 
2. Click the button to control input and button Switching of:
<td>
 <!-- Based on the current row inputVisible,To control input and button On demand Exhibition
 show-->
 <input type="text" class="form-control form-control-sm ipt-tag"
v-if="row.inputVisible" />
 <button type="button" class="btn btn-primary btn-sm" v-else
@click="row.inputVisible = true">+Tag</button>
 <span class="badge badge-warning ml-2" v-for="item in row.tags"
:key="item">{{item}}</span>
</td> 
5.3 Give Way input Get focus automatically
1. In App.vue Component, through directives Node customization v-focus The instructions are as follows:
directives: {
 // Encapsulates instructions that automatically gain focus
 focus(el) {
 el.focus()
 },
}
2. input Input box application v-focus Instruction:
<input type="text" class="form-control ipt-tag form-control-sm" vif="row.inputVisible" v-focus />
5.4 The text box is automatically hidden when it loses focus
1. use v-model Instruction handle input The value of the input box is bound to both directions row.inputValue Medium:
<input
 type="text"
 class="form-control ipt-tag form-control-sm"
 v-if="row.inputVisible"
 v-focus
 v-model.trim="row.inputValue"
/>
2. Monitor the of text box blur Event. When the event handler is triggered, the Data of current row Pass in:
<input
 type="text"
 class="form-control ipt-tag form-control-sm"
 v-if="row.inputVisible"
 v-focus
 v-model.trim="row.inputValue"
 @blur="onInputConfirm(row)"
/>
3. In App.vue Component methods Declaration under node onInputConfirm Event handler:
onInputConfirm(row) {
 // 1. Transfer the value entered by the user in the text box to the constant val in advance
 const val = row.inputValue
 // 2. Clear the value of the text box
 row.inputValue = ''
 // 3. Hide text box
 row.inputVisible = false
} 
5.5 Add new for item tag label
Further modification onInputConfirm The event handling functions are as follows:
onInputConfirm(row) {
 // The value entered by the user in the text box is transferred to the constant val in advance
 const val = row.inputValue
 // Clear the value of the text box
 row.inputValue = ''
 // Hide text box
 row.inputVisible = false
 // 1.1 judge whether the value of val is empty. If it is empty, it will not be added
 // 1.2 judge whether the value of val already exists in the tags array to prevent repeated addition
 if (!val || row.tags.indexOf(val) !== -1) return
 // 2. push the content entered by the user into the tags array of the current row as a new tag
 row.tags.push(val) }
5.6 Press enter in response to the text box
When the user clicks in the text box enter key You also want to be able to add the current input as tag label. At this point, you can bind the text box keyup The events are as follows:
<input
 type="text"
 class="form-control ipt-tag form-control-sm"
 v-if="row.inputVisible"
 v-focus
 v-model.trim="row.inputValue"
 @blur="onInputConfirm(row)"
 @keyup.enter="onInputConfirm(row)"
/>
5.7 Of the response text box esc Key
When the user clicks in the text box esc When you press the key, you want to be able to quickly empty the contents of the text box. At this point, you can create a text box
binding keyup The events are as follows:
<input
 type="text"
 class="form-control ipt-tag form-control-sm"
 v-if="row.inputVisible"
 v-focus
 v-model.trim="row.inputValue"
 @blur="onInputConfirm(row)"
 @keyup.enter="onInputConfirm(row)"
 @keyup.esc="row.inputValue = ''"
/>

Summary

① Know how to use ref to reference DOM and component instances

Specify the name of the reference through the ref attribute and use this$ Refs access reference instance

② Be able to know the calling time of $nextTick

The callback in $nextTick is not executed until the DOM of the component is updated

③ Be able to say the function of keep alive element

Status of dynamic components

④ Be able to master the basic usage of slots

< slot > tag, named slot, scope slot, v-slot: abbreviated as#

⑤ Know how to customize instructions

Private custom instruction, global custom instruction

Topics: Javascript Front-end Vue.js