Basic Operation of form
Gets the value of the checkbox
-
To pass the V-Model, you must also have the value attribute. The value value cannot be the same
<! -- 1. Two checkboxes need to be bidirectional bound with a value through v-Model. 2. Each checkbox must have the value attribute and the value value cannot be the same The gender value is the selected value, we just need to monitor it in real time --> <input type="radio" id="male" value="1" v-model='gender'> <label for="male">male</label> <input type="radio" id="female" value="2" v-model='gender'> <label for="female">female</label> <script> new Vue({ data: { // By default, the box with the current value of 2 is selected gender: 2,}})</script> Copy the code
Get the check box
- Through the v – model
- There must also be a value attribute. The values cannot be the same
- Check box
checkbox
So when we do this, we have to define the hobby in data as an array or we won’t be able to do multiple selection
<! Each check box must have a value attribute and the value cannot be the same. 3. When a certain box is selected, v-Model will change the current value to the data in data The value of Hobby is the selected value, and we just need to monitor its value in real time -->
<div>
<span>Hobbies:</span>
<input type="checkbox" id="ball" value="1" v-model='hobby'>
<label for="ball">basketball</label>
<input type="checkbox" id="sing" value="2" v-model='hobby'>
<label for="sing">Sing a song</label>
<input type="checkbox" id="code" value="3" v-model='hobby'>
<label for="code">Write the code</label>
</div>
<script>
new Vue({
data: {
// By default, the box with the current value of 2 and 3 will be selected
hobby: ['2'.'3',}})</script>
Copy the code
Gets the value of the drop-down box and the text box
-
Through the v – model
-
Each option in the drop-down box must have a value attribute and the value cannot be the same
<div> <span>Career:</span> <! Each option must have a value attribute and the value cannot be the same. 3. When an option is selected, v-Model will change the current value to data The value of occupation is the selected value, and we only need to monitor its value in real time --> <! -- multiple options --> <select v-model='occupation' multiple> <option value="0">Please choose a career...</option> <option value="1">Teachers'</option> <option value="2">Software engineer</option> <option value="3">The lawyer</option> </select> <! Textarea is a double tag that does not bind the value attribute --> <textarea v-model='desc'></textarea> </div> <script> new Vue({ data: { // By default, the drop-down box with the current value of 2 and 3 will be selected occupation: ['2'.'3'].desc: 'nihao'}})</script> Copy the code
Form modifier
.number
Convert to number
-
The default value in the form field is a string, which needs to be converted to the number type for numeric operations
<! -- Automatically convert user input to numeric type --> <input v-model.number="age" type="number"> Copy the code
.trim
Remove the first and last blanks
-
Automatically filter the first and last whitespace characters entered by the user
-
Only the first and last Spaces can be removed, but the middle Spaces cannot be removed
<! -- Automatically filter the first and last whitespace characters entered by the user --> <input v-model.trim="msg"> Copy the code
.lazy
Switch the input event to the change event
-
The input event is only fired each time an input is made
-
The change event is triggered when you lose focus or press Enter
<! -- "change" delay synchronization update --> <input v-model.lazy="msg" > Copy the code
Custom instruction
Global custom directives (vue.directive)
- When the built-in instructions don’t fit our needs (some DOM elements do low-level operations, such as aggregating input boxes)
- Vue allows us to customize instructions
- Using a custom instruction triggers the hook function
- Self order official website cn.vuejs.org/v2/guide/cu…
When the page loads, this element gets focus (note: AutoFocus does not work on the mobile version of Safari). In fact, as long as you haven’t clicked on anything since opening the page, the input field should remain in focus.
<! To use custom instructions, simply prefix the element with 'v-' to form a form similar to the internal instructions 'v-if', 'v-text'. -->
<input type="text" v-focus>
<script>
// Note:
Vue. Directive ('focusA',function(){})
// 2. When using HTML, you can only use v-focus-a
// Register a global custom directive v-focus
Vue.directive('focus', {
// When the binding element is inserted into the DOM. Where EL is the DOM element, inserted is the hook function
inserted: function (el) {
// Focus element el: the element bound by the directive, which can be used to directly manipulate the DOM.el.focus(); }});newVue({el:'#app'
});
</script>
Copy the code
Global custom instruction (with arguments)
binding.value
Represents the data data itemel
The: directive can be used to directly manipulate the DOM.
<input type="text" v-color='msg'>
<script type="text/javascript">
/* Custom directive - with argument bind - is called only once, when the directive is first bound to an element
Vue.directive('color', {
// bind declares a cycle that is called only once, the first time a directive is bound to an element. This is where you can do one-time initialization
// el is the DOM element of the current custom directive
// Binding for a custom function parameter. The value passed by the custom property is contained in binding
bind: function(el, binding){
// Set the background color according to the parameters of the command
// console.log(binding.value.color)el.style.backgroundColor = binding.value.color; }});var vm = new Vue({
el: '#app'.data: {
msg: {
color: 'blue'}}});</script>
Copy the code
Local custom instructions
-
Local directives, you need to add the Directives option in the VUE instance. Use the same as global directives
-
Local directives can only be used within the current component
-
When a global instruction and a local instruction have the same name, the local instruction prevails
<input type="text" v-color='msg'> <input type="text" v-focus> <script type="text/javascript"> /* Custom instruction - local instruction */ var vm = new Vue({ el: '#app'.data: { msg: { color: 'red'}},// Local directives need to be defined in the Directives options directives: { color: { bind: function(el, binding){ el.style.backgroundColor = binding.value.color; }},focus: { inserted: function(el) { el.focus(); }}}});</script> Copy the code
Hook function
When a Vue instance is created and destroyed, it automatically calls some functions called hook functions
A custom instruction object can provide the following hook functions
bind
: is called only once, the first time a directive is bound to an element. This is where you can do one-time initialization.inserted
: called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily has been inserted into the document).update
: is called when the VNode of the component is updated.However, this may occur before the child VNode is updated. The value of the instruction 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 more details on the hook function arguments).
Hook function parameters
The directive hook function is passed the following arguments:
el
The: directive can be used to directly manipulate the DOM.binding
: An object containing the following properties:name
: Indicates the name of the directive, excludingv-
Prefix.value
: directive binding value, for example:v-my-directive="1 + 1"
, the binding value is2
.oldValue
: the previous value of the instruction binding, only inupdate
和componentUpdated
Available in hooks. It is available regardless of whether the value has changed.expression
: instruction expression in string form. For example,v-my-directive="1 + 1"
, the expression is"1 + 1"
.arg
: Parameter passed to the instruction. This parameter is optional. For example,v-my-directive:foo
, the parameter is"foo"
.modifiers
: An object containing a modifier. Such as:v-my-directive.foo.bar
, the modifier object is{ foo: true, bar: true }
.
vnode
: Virtual node generated by Vue compilation. movingVNode APITo learn more.oldVnode
: Indicates the last virtual node, only inupdate
和componentUpdated
Available in hooks.- For details, see cn.vuejs.org/v2/guide/cu…
Computed attributes
-
Putting too much logic in the interpolation can make the template too heavy and hard to maintain. Using computed properties can make using the template more concise
< --! Too much logic in interpolation --><div id="example"> {{ message.split('').reverse().join('') }} </div> Copy the code
-
Computed attributes are implemented based on data and also rely on responsive caching
-
Computed attributes are often used to process data associated with templates
-
Using the computed attribute requires a return result
<div id="app"> <! The value of num in the reverseString is not changed until the value of num in the reverseString is changed --> <div>{{reverseString}}</div> <div>{{reverseString}}</div> <! -- call the method (s) from the method (s) --> <div>{{reverseMessage()}}</div> <div>{{reverseMessage()}}</div> </div> <script type="text/javascript"> /* The difference between computed attributes and methods: Computed attributes are cached based on dependencies, while methods are not cached */ var vm = new Vue({ el: '#app'.data: { msg: 'Nihao'.num: 100 }, methods: { reverseMessage: function(){ console.log('methods') return this.msg.split(' ').reverse().join(' '); }},// Computed attribute definitions and data have been methods flat computed: { // reverseString This is our own name reverseString: function(){ console.log('computed') var total = 0; // When num in data is changed, the reverseString is calculated automatically for(var i=0; i<=this.num; i++){ total += i; }// Return the value of reverseString returntotal; }}});</script> Copy the code
The difference between computing attributes and methods methods
- The computed attribute is cached based on the responsive dependency of the data and is reevaluated only when the responsive dependency changes
- Methods are not cached and are executed as many times as they are accessed
- Why do you need to compute attributes to reduce performance overhead
The listener watch
-
A listener listens for changes in data
-
Perform the interface request by listening for changes in the value of the text input box binding
-
Usually used for expensive or asynchronous tasks such as Ajax requests
-
Properties in watch must be data that already exists in data
-
<div id="app"> <div> <span>Name:</span> <span> <input type="text" v-model='firstName'> </span> </div> <div> <span>Last name:</span> <span> <input type="text" v-model='lastName'> </span> </div> <div>{{fullName}}</div> </div> <script type="text/javascript"> /* Listener */ var vm = new Vue({ el: '#app'.data: { firstName: 'Jim'.lastName: 'Green'.// fullName: 'Jim Green' }, // Watch property definition and data have methods flat watch: { // Note: firstName corresponds to firstName in data // Watch is automatically triggered when the firstName value changes firstName: function(val) { this.fullName = val + ' ' + this.lastName; }, // Note: lastName corresponds to lastName in data lastName: function(val) { this.fullName = this.firstName + ' '+ val; }}});</script> Copy the code
The filter
-
Format data, such as capitalizing the first letter of a string, to format the date in the specified format
-
Two places filters can be used are interpolation and v-bind attribute expressions
-
Supports multiple filters used together (execution order is left to right)
-
The function of each filter remains single if there are multiple filter requirements declare multiple filters
-
Filters should be added at the end of JavaScript expressions
-
The filter does not change the actual data, but only changes the rendered result and returns the result by return
-
If a global filter has the same name as a local filter, the local filter is used
-
Global registration is filter, do not need to add s.
-
Local registrations are filters, so add s
Vue3.0 has removed filters and does not support using computed attributes or methods to replace filters
Read more ⚠️ : vue3js.cn/docs/zh/gui…
Global filter
<div id="app">
<input type="text" v-model='msg'>
<! -- upper is defined as a filter function that takes a single argument, and the value of the expression MSG is passed in as an argument -->
<div>{{msg | upper}}</div>
<! Upper is defined as a filter function that takes a single argument, and the value of the expression MSG is passed as an argument to the function. It then continues to call filter lower, which is also defined to take a single argument, passing the result of upper into lower -->
<div>{{msg | upper | lower}}</div>
<div :abc='msg | upper'>The test data</div>
</div>
<script type="text/javascript">
// Lower indicates the global filter name
Vue.filter('lower'.function(val) {
// Filter logic code
return val.charAt(0).toLowerCase() + val.slice(1);
});
var vm = new Vue({
el: '#app'.data: {
msg: ' '}});</script>
Copy the code
Partial filter
<div id="app">
<input type="text" v-model='msg'>
<! -- upper is defined as a filter function that takes a single argument, and the value of the expression MSG is passed in as an argument -->
<div>{{msg | upper}}</div>
<! Upper is defined as a filter function that takes a single argument, and the value of the expression MSG is passed as an argument to the function. It then continues to call filter lower, which is also defined to take a single argument, passing the result of upper into lower -->
<div>{{msg | upper | lower}}</div>
<div :abc='msg | upper'>The test data</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app'.data: {
msg: ' '
},
// Filters attribute definition and data methods flat
// Define the filters in the filters as local filters
filters: {
// upper Specifies the name of the user-defined filter
// Upper is defined as a filter function that takes a single argument. The value of the expression MSG is passed as an argument to the function
upper: function(val) {
// The filter must have a return value so that the outside world can use the filter to get the result
return val.charAt(0).toUpperCase() + val.slice(1); }}});</script>
Copy the code
Filter to pass parameters
- Pass parameters in parentheses when using filters
- Start with the second parameter with the filter parameter
<div id="box">
<! FilterA is defined as a filter function that takes three arguments. The value of message is the first argument, the normal string 'arg1' is the second argument, and the value of the expression arg2 is the third argument. -->
{{ message | filterA('arg1', 'arg2') }}
</div>
<script>
// The first parameter in the filter corresponds to the data before the pipe character n, which in this case corresponds to message
// The second argument a corresponds to the arg1 string
// The third argument b corresponds to the arg2 string
Vue.filter('filterA'.function(n,a,b){
if(n<10) {return n+a;
}else{
returnn+b; }});new Vue({
el:"#box".data: {message: "Ha ha ha."}})</script>
Copy the code
Date formatting rules
<div id="app">
<div>{{date | format('yyyy-MM-dd hh:mm:ss')}}</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/* Filter case: format date */
// Vue.filter('format', function(value, arg) {
// The disadvantage is that the date format is single
// if(arg == 'yyyy-MM-dd') {
// var ret = '';
// ret += value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate();
// return ret;
/ /}
// return value;
// })
Vue.filter('format'.function(value, arg) {
// This is a date formatting rule
function dateFormat(date, format) {
if (typeof date === "string") {
var mts = date.match(/(\/Date\((\d+)\)\/)/);
if (mts && mts.length >= 3) {
date = parseInt(mts[2]);
}
}
date = new Date(date);
if(! date || date.toUTCString() =="Invalid Date") {
return "";
}
var map = {
"M": date.getMonth() + 1./ / in
"d": date.getDate(), / /,
"h": date.getHours(), / / hour
"m": date.getMinutes(), / / points
"s": date.getSeconds(), / / SEC.
"q": Math.floor((date.getMonth() + 3) / 3), / / quarter
"S": date.getMilliseconds() / / ms
};
format = format.replace(/([yMdhmsqS])+/g.function(all, t) {
var v = map[t];
if(v ! = =undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + ' ').substr(4 - all.length);
}
return all;
});
return format;
}
// Call the date formatting function
return dateFormat(value, arg);
})
var vm = new Vue({
el: '#app'.data: {
date: new Date()}});</script>
Copy the code
The life cycle
- The process from birth to death
- The process of creating and destroying a Vue instance is accompanied by self-calling functions called hook functions
The main stage
- Mount (initialize related properties)
- beforeCreate
- created
- beforeMount
- mounted
- update
- beforeUpdate
- updated
- The destruction
- beforeDestroy
- destroyed
Commonly used hook functions
beforeCreate | It’s called after the instance is initialized, before the data observation and event configuration at which point the data and methods and the DOM structure of the page are not initialized and nothing can be done, okay |
---|---|
created | It’s called immediately after the instance has been created when data and methods are available but the page has not yet been rendered |
beforeMount | It’s called before the mount starts and you don’t have any real data on the page yet it’s just a template page |
mounted | El is replaced by the newly created VM.$el, and the hook is called after the instance is mounted. The data is actually rendered to the page and we can use some third party plug-ins in this hook function |
beforeUpdate | Called when data is updated, before the virtual DOM is patched. The data on the page is still old |
updated | This hook is called after the virtual DOM is rerendered and patched due to data changes. The data on the page has been replaced with the latest one |
beforeDestroy | Called before instance destruction |
destroyed | Called after instance destruction |
Array mutation method
- In Vue, modifying the value of an object property directly does not trigger a response. When you directly modify the value of the object property, you will notice that only the data changes, but the page content does not change
- Mutated array method is to keep the original function of array method unchanged under the premise of its function expansion
- These methods affect the raw data and are processed by Vue as reactive data
push() |
Returns the length of the current array successfully by adding an element to the end of the array |
---|---|
pop() |
Deletes the last element of the array. Returns the value of the deleted element successfully |
shift() |
Deletes the first element of the array, and returns the value of the deleted element successfully |
unshift() |
Returns the length of the current array successfully by adding an element to the beginning of the array |
splice() |
There are three arguments, the first is the index of the element you want to delete (mandatory), the second is the number of elements you want to delete (mandatory), and the third is the value you want to replace at the original place after deletion |
sort() |
Sort () sorts the array from small to large by default, and returns the sorted array successfully |
reverse() |
Reverse () reverses the array, successfully returning the reversed array |
Replace the array
- Does not change the original array, but always returns a new array
- These methods do not change the original array, so they do not change the data in the template
filter | The filter() method creates a new array by examining all the elements in the specified array that meet the criteria. |
---|---|
concat | The concat() method is used to join two or more arrays. This method does not change the existing array |
slice | The slice() method returns the selected elements from an existing array. This method does not modify the array, but returns a subarray |
Dynamic array responsive data
- Vue.set (vm.items, index, newValue)
- Vm. $set (vm.items, index, newValue)
- Parameter 1 indicates the name of the array to be processed
- Parameter 2 indicates the index of the processing array
- Parameter three represents the value after processing the array
Dynamic object reactive data
- Vue.set (vm.items, index, newValue)
- Vm. $set (vm.items, index, newValue)
- Parameter 1 indicates the name of the object to be processed
- Parameter two represents the name of the property of the object to be processed
- Parameter three indicates the value of the processed object
Introduction to Vue Basics (I)
“Likes, Favorites and comments”
❤️ Follow + like + add + comment + forward ❤️, encourage me to create better articles, thank you 🙏 everyone.