Basic overview of vue
The > element is a built-in component inside Vue.
Vue (pronounced /vjuː/, similar to view) is a set of progressive frameworks for building user interfaces.
Vue.js is a progressive framework for building user interfaces, designed with incremental development from the bottom up. Vue's core libraries focus on views (html), making them easy to use and integrate with third-party libraries or projects.
Progressive: step by step, not learning everything before using it.
Bottom-up design: A process and method of designing a program, that is, first write the basic program segments, and then gradually expand the specification, supplement and upgrade certain functions, which is actually a process of constructing the program from the bottom up.
At the heart of Vue.js is a system that allows declarations using a concise template syntax to render data into the DOM
A declaration of advancement is required before the data can be used
Why Learn Vue?
Simple, the three front-end frameworks (Vue, React, angler) are the most friendly frameworks for beginners
On the other hand, when combined with modern toolchains and a variety of supporting libraries, Vue is also perfectly capable of powering complex single-page applications.
What is the difference between Vue and Jquery?
Data-driven attempts
-
The transition from jquery to vue is a change of thinking, which is to change the idea of directly operating DOM in jquery to manipulating data.
-
jQuery uses selectors to select DOM objects, assign values, take values, bind events, etc., in fact, the difference from native HTML is only that it can select and operate DOM objects more conveniently
-
Vue completely separates data and views through Vue objects. It can be said that data and views are separated, and they bind each other through Vue objects. This is the legendary MVVM
When to learn Vue?
Familiarize yourself with the front-end three-piece set (HTML, CSS, JavaScript)
Vue basic syntax
Official documentation
Interpolation Expressions
Use {{ }} to render the variables in data:{}
It can also be a function, but the method in data needs to add braces in the interpolation expression
For example
HTML
<div id="app">
<div>{{ msg }}</div>
<div>{{ getInfo() }}</div>
</div>
In interpolation expressions, operators are supported, as well as some methods
vue command:
v-text
Render text, similar to interpolation expressions
HTML
<div></div>
<div>{{ msg }}</div>
It also supports operators
HTML
<div></div>
v-html
Render labels, if the string is a special character with a label, then vue will render it as a label
If it is v-text or an interpolated expression is used, it will output as is
Note:
v-html is generally used to render trusted text, such as the details of an article, and it is best not to use it in user submissions
It is easy to cause XSS attacks
v-bind
You can dynamically add content to tags, or you can dynamically modify tag properties
However, the operation on the properties is slightly different from the operation content, we use the 'v-bind' command
For example, I want to dynamically modify the src attribute of the img tag to read the value in the data
But we can't use interpolation expressions in properties
Writing src directly outputs my content as it is, so we need to use v-bind, which stands for dynamic properties
Then I can do that
HTML
<img alt="">
Of course, 'v-bind:' can be abbreviated as ':'
HTML
<img alt="">
v-bind can be used not only for properties that exist in HTML, but also for custom properties
For example
HTML
<p></p>
Actual results:
<p id="p_01"></p>
All of Vue's directives support expressions
For example:
JavaScript
<div class="name">
{{ a.length === 0 ? 'No data' : a }}
-{{ a.split('.') [1] }}
</div>
What is an expression?
JavaScript
This is the statement
var a = 1;
This is the expression
a.length === 0 ? 'No data' : a
Conditional Rendering
Common use of v-if and v-else
If the boolean value in v-if is true, then this div is rendered
If the if doesn't hold, render the code block in else
HTML
<div id="app">
<div>{{ num }}</div>
<div id="if">
<div>Probability greater than 0.9</div>
<div>v-if does not satisfy showing me</div>
</div>
</div>
v-else-if multi-conditional statements
HTML
<div id="v-else-if">
<div>Probability greater than 0.9</div>
<div>Probability greater than 0.6</div>
<div>Probability greater than 0.4</div>
<div>Probability greater than 0.2</div>
<div>All conditions are not true</div>
</div>
v-if="flag", which is displayed when true
disappears when false
JavaScript
<div id="app">
<div class="name">
{{ name }}
</div>
<div>
If it doesn't match, it shows me
</div>
</div>
Difference Between V-Show and V-If
-
If v-if is false, it will not be rendered
-
v-show will not display ' style="display: none if it is false; "`
Experience V-IF and V-SHOW
HTML
One is invisible, but I exist, only I hide the v-show
One is invisible because I wasn't rendered v-if in the first place
List rendering
It is mainly divided into traversal lists and traversal objects
Iterate through the list
JavaScript
lis: [
'Zhang San',
'Wang Wei',
'Zhang Wei',
'Wang Wu',
]
The item at this point is each element
HTML
<ul>
<li>
{{ item }}
</li>
</ul>
key to be unique!!
If you need to iterate through the index of each element
then specify the index during traversal
HTML
<ul>
<li>
{{ index }} -- {{ item }}
</li>
</ul>
Traverse the object
JavaScript
obj:{
name: 'Zhang San',
age: 21,
addr: 'Beijing',
}
A parameter is the value of the traversal object
Two parameters, a value and a key
Three parameters, values, keys, indexes
HTML
<ul>
<li>
Value of object: {{ item }}
</li>
</ul>
<ul>
<li>
Value of object: {{ item }}
Object's key: {{ key }}
</li>
</ul>
<ul>
<li>
Value of object: {{ item }}
Object's key: {{ key }}
Index of variables: {{ index }}
</li>
</ul>
Vue Events
v-on: or @
HTML
<div id="app">
<div>
{{ num }}
</div>
<div>
<button>Click Me +</button>
<button>Tap me -1</button>
</div>
</div>
The methods by which an event is executed are to be defined in the methods
JavaScript
methods: {
add() {
this.num ++
}
}
Parameter problem
Parameter passing can be done by passing parameters
HTML
<button>Click Me +</button>
...
add(number) {
this.num += number
}
At this time, the add function can receive the parameter values passed in
Default parameters
The default parameter is the event object that triggers the current event
JavaScript
<button id="add" class="add_cls"> click me +</button>
It must be 'v-on:click="add"', just write a function name,
Instead of 'v-on:click="add()"', you won't get the event object
JavaScript
Get the label that triggers the current event
add(event) {
The event object that triggers the current event
console.log(event)
Get the label
console.log(event.target)
Get the id, class
console.log(event.target.id)
console.log(event.target.className)
}
If there are parameters, you want to receive the event object
Use '$event' for passing
JavaScript
<button id="add" class="add_cls"> click me +</button>
...
add(number, event) {
this.num += number
The event object that triggers the current event
console.log(event)
Get the label
console.log(event.target)
Get the id, class
console.log(event.target.id)
console.log(event.target.className)
}
Image carousel case
HTML
<title>Picture carousel</title>
<div id="app">
<div>
<img alt="">
</div>
<div>
<button>Previous</button>
<button>Next one</button>
</div>
</div>
Event modifiers
Calling event.preventDefault() or event.stopPropagation()' in the event handler is a very common requirement. While we can easily do this in the method, it would be better to do it in a way that only has pure data logic instead of dealing with DOM event details.
To solve this problem, Vue.js provides an event modifier for 'v-on'. As mentioned earlier, the modifier is represented by a command suffix that starts with a dot.
HTML
<a></a>
<form></form>
<a></a>
<form></form>
<div>...</div>
<div>...</div>
<a href="http://www.fengfengzhidao.com"> Fengfeng knows</a>
Event bubbles
HTML
<div class="parent">
<div class="center">
<div class="child">
</div>
</div>
</div>
Click on the element to execute the order
Click the element in the middle
Elements wrapped in the parent element will pass the event upwards step by step after clicking Send event
HTML
<p>Stop the event from bubbling</p>
<div class="parent">
<div class="center">
<div class="child">
</div>
</div>
</div>
After adding the stop event modifier, clicking on the inside element will prevent the event from continuing to propagate upwards
Keyboard events
HTML
@keydown Keyboard press
@keyup Keyboard bounce
Press enter to trigger
Support key combinations
HTML
<input type="text">
<input type="text">
When using modifiers, order is important; the corresponding code is generated in the same order. Therefore, using 'v-on:click.prevent.self' will block all clicks, while 'v-on:click.self.prevent' will only block clicks on the element itself.
Added in 2.1.4
HTML
<a></a>
Key modifiers
The most common possibility is to determine whether the user has pressed enter in an input box
HTML
<input>
Some necessary key names
HTML
.enter
.tab
.delete (captures the "delete" and "backspace" keys)
.esc
.space
.up
.down
.left
.right
Combination of buttons
HTML
<input>
<div>Do something</div>
Calculate Attributes
-
No parentheses (just an attribute) when calling
-
You can listen for attribute changes, change attributes, and calculate attributes to re-execute
-
And there is a cache (multiple calculated properties, executed only once)
and methods
The attributes change, and the methods method is all reacquired
HTML
<title>Calculate attributes</title>
<div id="app">
<div>{{ name }}</div>
<div>{{ name.split('').reverse().join('') }}</div>
<div>{{ name.length === 5 ? 'Five-character quatrain' : 'Seven-character quatrain' }}</div>
<div>A five-character quatrain</div>
<div>Seven-character quatrain</div>
<div>Wrong</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ getName }}</div>
<div>{{ get_data_name() }}</div>
<div>{{ get_data_name() }}</div>
<div>{{ get_data_name() }}</div>
<div>{{ get_data_name() }}</div>
<div>{{ get_data_name() }}</div>
<button>
Click me
</button>
<span>{{ num }}</span>
<button>Calculate attributes</button>
</div>
Difference between computed and watch, methods
methods: can put in a function, and there is no cache
watch:
Listening, which is triggered only when the data is sent to change
You can get the present value and the past value
You can also listen for route changes
It has the same name as the attribute
Custom filters
Create a filter
JavaScript
Custom filters
filters:{
Capture the last character
getLastChar(item){
return item.substr(item.length-1,1)
}
}
Use filters
HTML
<li>
{{item.name|getLastChar }} -- {{ item.addr }}
</li>
Time filter
HTML
<div id="app">
<div>
Current time: {{ now|get_date }}
</div>
<ul>
<li>
id:{{ item.id }} Time:{{ item.date|get_date }}
</li>
</ul>
<div>
Time filtering
</div>
<ul>
<li>
id:{{ item.id }} Time:{{ item.date|time_to_filter }}
</li>
</ul>
</div>
Parameter issues
Custom filters are also acceptable parameters, and their writing syntax is
JavaScript
<li>
id:{{ item.id }} Time:{{ item.date|time_to_filter('a', 'b') }}
</li>
...
filters: {
...
time_to_filter(date_str, a, b) {
date_str -> 'Own value'
// a -> 'a'
// b -> 'b'
return date_str
}
}
The first parameter of the filter method is the value of the caller itself, and the second parameter is followed by the calling argument
And it supports chain filters
HTML
<div>{{now|get_now|get_now1}}</div>
Global Approach
Properties and methods need to be mounted on 'Vue.prototype'
JavaScript
Vue.prototype.$com = "Global Variable"
let global_method = ()=>{
return "global approach"
}
function add(){
return "Global Add Method"
}
Vue.prototype.$global_method = global_method
Vue.prototype.$add = add
use
HTML
<div>
{{ $global_method() }}
</div>
<div>
{{ $add() }}
</div>
Global Filters
JavaScript
Global filters
let global_filter = (item) => {
return item + '--global'
}
Register a global filter (filter name, method)
Vue.filter('global_filter', global_filter)
Use global filters
HTML
<div>
{{ $com|global_filter }}
</div>
Local Components
HTML
<title>Local components</title>
<div id="app">
</div>
Global Components
HTML
<title>Local components</title>
<div id="app">
</div>
Component Communication
Father to son
Parent-to-child transmission: Communication is carried out through 'props'
HTML
1. Declare props in the self-component to receive the attributes mounted on the parent component
2. You can use any template of your own component
3. Bind custom properties to the parent component
props pass in an object
JavaScript
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise // or any other constructor
}
props: {
data: {
type: String, // type
required: true, // required
default: 'Zhang San' // If no value is passed, then this default value is it
}
}
HTML
<div id="app">
</div>
created and mounted
JavaScript
created(){
console.log(this.data, 1)
},
mounted(){
console.log(this.data, 2)
}
The son inherits the father
HTML
1. In the parent component, bind custom events from the component
2. In the self-component, trigger a native event, and trigger a custom event in the event function via this.$emit
Parent component
JavaScript
components: {
comment1
},
methods: {
eff(data) {
data is the data passed by the child component
console.log('Parent component called', data)
}
}
Sub-components
JavaScript
let comment1 = {
template: `
<div>
<ul>
<li>Lanzhou ramen</li>
<li>Harbin Beer</li>
<li>Sichuan Dandan Noodles</li>
<button>Click I trigger the parent component method</button>
</ul>
</div>`,
methods: {
add() {
this.$emit('eff', {name: 'data from subcomponents'})
}
}
}
Parallel Components
HTML
<title>Parallel components</title>
<style>
body {
margin: 0;
}
#app {
display: flex;
}
#app > div {
width: 50%;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
#gouwuc {
background-color: #3a8ee6;
}
#get {
background-color: #b3d9d9;
}
</style>
<div id="app">
</div>
Nested values multiple times
HTML
1. provide variable function (){return {} },
2. inject receive variable inject: [],
Anonymous Slots
JavaScript
let base_layout = {
data() {
return {}
},
template: `
<div>
<header>
I'm the header
</header>
</div>`
}
new Vue({
el: '#app',
components: {
base_layout
}
})
Put what you want to replace in the template in the tab, that's a placeholder
HTML
Actual content
This will replace the content in the tag with the content in the slot
If none of the slots have names, then if there are multiple slots, they will all be replaced
Named Slots
If you have multiple places in your template that need to be replaced
Then anonymous slots are not suitable, we give each slot an alias
JavaScript
let base_layout = {
data() {
return {}
},
template: `
<div>
<header>
I'm the header
</header>
<main>
I am the content
</main>
<footer>
I am the footer
</footer>
</div>`
}
In this way, when we make a replacement, we can specify which slot to replace
HTML
<template>
head
</template>
<template>
body
</template>
<template>
Tail
</template>
Pay attention to the way the v-slot is written
HTML
v-slot:header
'v-slot:' can be shortened to #
HTML
<template>
<div>
Hahahaha
</div>
</template>
<template>
body
</template>
<template>
Tail
</template>
We can write any label when replaced, that is, you can also write components into the slot when replaced
HTML
<template>
<div>
Hahahaha
</div>
</template>
<template>
body
</template>
<template>
Tail
</template>
Scope slots
JavaScript
let base_layout = {
data() {
return {
user: {
name: 'Maple Maple',
xin: 'Know'
}
}
},
template: `
<div>
<main>
{{ user.xin }}
</main>
</div>`
}
In the subcomponent, I show the user's xin in the slot, what should I do if I want it to show the user's name?
If we write it like this directly when the parent component is called
HTML
{{ user.name }}
This is a wrong way to write it, because our user is defined from the component, and this user cannot be used in the parent component, so an error will be reported
Then we should pass this user object to the parent component
in the sub-component
HTML
{{ user.xin }}
Pass user to the parent component through dynamic properties
in the parent component
HTML
<template>
{{ slotProps.user.name }}
</template>
Receive the delivered user
slotProps can be a name that you define yourself, and it stores something like this
HTML
{ "user": { "name": "Fengfeng", "xin": "Know" } }
So we pass the name in the user in slotProps to the subcomponent, and we can achieve dynamic data replacement
If you have and only one default slot in your component, you can do this when replacing it
HTML
{{ slotProps }}
However, if a named slot appears, it can cause scope confusion
We should use it this way
JavaScript
let base_1 = {
data(){
return {
user: {
name: 'Maple Feng Knows',
age: 21
}
}
},
template: `
<div>
<header>
My name is {{ user.name }} and my age is {{ user.age }}
</header>
</div>`
}
HTML
<template>Zhang Zifeng</template>
<template>{{ slotBase }}</template>
Dynamic components
Using v-bind: is in it, you can achieve the effect of dynamic components.
Custom Instructions
The previous use of v-if, v-show, and v-for are all built-in instructions provided by Vue
Of course, we can also customize a command ourselves
Local custom instructions
JavaScript
directives: {
focus: {
Definition of directive
Using this command will focus on the input box
inserted: function (el) {
el.focus()
}
}
}
use
HTML
<input type="text">
There are several hook functions in focus that need to be understood
- 'bind': Call only once, the command is called when it is first bound to an element. A one-time initialization can be made here.
- 'inserted': Called when the bound element is inserted into the parent node (only guarantees that the parent node exists, but not necessarily already inserted into the document).
- 'update': Called when the component's VNode is updated, but may occur before its child VNode is updated. The value of the directive may or may not have changed. However, you can ignore unnecessary template updates by comparing the values before and after the update (see below for detailed hook function parameters).