1. Filters
Concept: vue.js allows for custom filters and can be used as some common text formatting (further processing of data)
Filters are only used in two places: mustache interpolation expression, v-bind expression
The filter should be added to the end of the JavaScript expression, indicated by the "pipe" symbol (pipe: |)
-
Global filter:
Syntax: Vue.filter('filter name','filter its handler (callback function)'); -
Private filter: --- Defined in Vue
Syntax: filters:{}- Invoke filter: {{item|filter name}}
- Parameters can be passed when calling the filter: {{item|filter name (parameter list)}
-
Notes for use of filters:
- In the filter's processing function, the first parameter function is defined, always the value before the pipe symbol.
- Parameters passed by the calling filter can only be received from the second person parameter of the processing function
- Returns a value from the filter's handler
- Multiple filters can be called continuously using pipe characters
- Using vue's filter does not modify the original data, it just wraps it up while displaying it
2. Custom directives
Customize global directives:
Veu.directives('Name of instruction',{ bind:function(){}, // When an element bound to an instruction is resolved by a Vue instance, the bind function is executed immediately, so bind executes first inserted:function(){}, // Call the inserted function when the element of the bound instruction is inserted into the parent node of the document })
Be careful:
- When customizing instructions, it is best to write the js behavior of the elements to inserted, and styles to bind and inserted
Customize private directives:
directives:{ // Custom instruction instruction name is a key and instruction value is an object bold:{ bind(el,binding){ el.style.fontWeight = binding.value; }, inserted(el){ } },
Short form of custom private directives:
italic:function(el,binding){ // The abbreviated form of a function used for an instruction is equivalent to defining the code in that function into bind and update, respectively, if the instruction is given a function el.style.fontStyle='italic'; }
3. Life cycle of vue instance
- What is a life cycle: From Vue instances created, run, to destruction, there are always a variety of events that are collectively referred to as life cycles
- Lifecycle Function=Hook Function=Lifecycle Event
Master the differences between beforeCreate and create, beforeMounted and mounted
liulongbin notes
4. vue-resource implements get, post, jsonp requests
Note: vue-resource can only be imported after the Vue package
Common types of data requests: get, post, jsonp
<div id="app"> <input type="button" value="Get request" @click='getInfo'> <input type="button" value="Post request" @click='postInfo'> <input type="button" value="JSONP request" @click='jsonpInfo'> </div> <script> var vm=new Vue({ el:'#app', data:{}, methods:{ // async and await allow us to request data in a manner similar to asynchronous requests async getInfo(){ // Not written.then() // const result = await this.$http.get("http://api.cms.liulongbin.top/api/getlunbo"); // Deconstruction assignment to get the value of body in the return value is recommended: const { body } = await this.$http.get('http://api.cms.liulongbin.top/api/get'); console.log(body); }, async postInfo(){ const { body } = await this.$http.post('http://api.cms.liulongbin.top/api/post',{name:'flower', age:18, gender:'man'}; console.log(body); }, async jsonpInfo(){ const { body } = await this.$http.jsonp( 'http://api.cms.liulongbin.top/api/jsonp'); console.log(body); } } }); </script>
5. axios sends requests in conjunction with vue
axios does not support jsonp requests
<div id="app"> <input type="button" value="get request" @click='getInfo'> <input type="button" value="post request" @click='postInfo'> </div> <script> // Mount axios on the Vue prototype Vue.prototype.$http = axios var vm=new Vue({ el:'#app', data:{}, methods:{ async getInfo(){ // Common Writing: // const { data } = await axios.get('http://api.cms.liulongbin.top/api/getlunbo'); // console.log(data); // Requirement: If you want axios to be able to use this.$http.get, you need to mount axios onto the Vue's prototype object because this points to an instance of Vue const {data} = await this.$http.get('http://api.cms.liulongbin.top/api/getlunbo') console.log(data); }, async postInfo(){ const {data} = await this.$http.post('http://api.cms.liulongbin.top/api/post'); console.log(data); } } }); </script>
6. Cross-domain
What is cross-domain: Cross-domain is the result of browser homology policy and is inaccessible to clients and servers under different protocols, ports, domains (any of the above differences are cross-domain)
- http://www.baidu.com/index.html call http://www.baidu.com/server.php (not cross-domain)
- http://www.baidu.com/index.html call http://www.csdn.com/server.php (Primary domain name is different: baidu/csdn, cross-domain)
- http://abc.baidu.com/index.html call http://def.baidu.com/server.php (Subdomain name is different: abc/def, cross-domain)
- http://www.baidu.com:8080/index.html call http://www.baidu.com:8081/server.php (Ports are different: 8080/8081, cross-domain)
- http://www.baidu.com/index.html call https://www.baidu.com/server.php (Protocol is different: http/https, cross-domain)
- Note: Both localhost and 127.0.0.1 are native, but also cross-domain
7. Principle of jsonp
You can dynamically create a script tag to point the src attribute of the script tag to the address of the data interface, because there is no cross-domain restriction on the script tag, which is called JSONP (the src attribute of the script tag is not constrained by homology policy, so you can fetch and execute scripts on any server)
jsonp, short for JSON with padding, is an unofficial protocol that allows Script tags to be inherited on the server side and returned to the client side for cross-domain access via javascript callback
1) Simulate jsonp:
<!-- Amount to jsonp Principle: --> <!-- Equivalent to local --> <script> function success(data){ console.log(data); } </script> <!-- Equivalent to dynamically created script <script> success(1); </script>
2) jsonp requests local files:
<script> function success(data){ console.log(data); } </script> <!-- Request one remotely js File and parse execution --> <script src="./script.js"></script>
<!-- script.js--> success(123);
3) jsonp requests files on the server:
<script> function success(data){ console.log(data); } </script> <!--Pass in a callback function--> <script src="http://127.0.0.1:3000/api/getjsonp?callback=success"></script>
// Introduce core modules: const http = require('http'); // New http.Server instance (create server): const server = http.createServer(); //Introduce the url module: const urlModule = require('url'); // Binding port number (3000): server.listen(3000, ()=>{ console.log('http://127.0.0.1:3000'); }); // Listen for client-initiated requests: server.on('request', (req, res)=>{ // Deconstruct the required pathname and query attributes by parsing and transforming with the url module and using the deconstruction assignment of objects const {pathname:myurl,query} = urlModule.parse(req.url,true); // const result = new URL(req.url,'http://127.0.0.1:3000'); const person = { name:"Land and Land", age:18, gender:'male' } if(myurl === '/api/getjsonp'){ // Serialize the object as a string using JSON.stringify(), since the parameters passed in are of type string const str = `${query.callback}(${JSON.stringify(person)})`; res.end(str); }else{ res.end('404'); } });
8. Simply create a server using node.js
1. First, let's understand that Node.js is not a language, it's just an environment that runs JS in addition to the browser
2. Secondly, what can Node do? web Server, Command Line Tools, web Crawler, Desktop Application Development, etc.
3. Create a simple server using Node.js:
// Introduce the core module of node: var http = require('http'); // Create a server object: var server = http.createServer(); // Start the http service and set the port: server.listen(3000,function(){ console.log('Start Successful'); }); // Add (bind) client request events to the server: server.on('request',funtion(req,res){ console.log('Server Request'+req.url); // Response Disconnected res.end(); })
9. url module of node.js:
The URL module provides some useful functions for URL processing and parsing
const url = require('url'); // Introducing url modules
1. URL strings and URL objects: URL strings are structured strings that contain multiple components of different meanings. A URL string can be parsed into a URL object whose properties correspond to the components of the string
2. The URL module provides two sets of APIs to handle URL strings: one is unique to Node.js and is a legacy of the old version; Another is the API that implements the WHATWG URL Standard, which is also used in various browsers
Note: Although the specific API left behind by Node.js has not been discarded, we keep it for compatibility with existing applications only. So new applications should use the WHATWG API
(1) Resolve a URL string using the WHATWG API:
const { URL } = require('url'); const myURL = url.parse('http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');
In browsers, WHATWG URL s are globally available, whereas in Node.js, a link must be opened or used in advance by referencing the'url'module: require('url').URL
(2) Resolve a URL through the API provided by Node.js:
const url = require('url'); const myURL = url.parse('http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');
10. Database Version - Brand Management:
methods:{ async getList(){ const { data } = await this.$http.get('http://www.liulongbin.top:3005/api/getprodlist') console.log(data); // Give the data to the list to save // If the data request succeeds, mount the data results on the data for use by the page if(data.status === 0)this.list = data.message; }, async add(){ if(this.name.trim().length <= 0) return alert('Brand name cannot be empty!'); const {data} = await this.$http.post('http://www.liulongbin.top:3005/api/addproduct',{name:this.name.trim()}); // If successful, call the method to get the data again if(data.status === 0)this.getList() }, async del(id){ // Remove brand based on id const {data} = await this.$http.get('/api/delproduct/' + id); if(data.status === 0) this.getList(); } }
11. vue animation:
Concept: Vue splits a complete animation into two parts: an entry animation and an exit animation
Entry animation consists of two time points, before (v-enter) and after (v-enter-to)
v-enter represents the starting state before the animation enters, such as 0 transparency and 50 PX lateral offset
v-enter-to denotes the end state of the animation after it has entered the arena, such as transparency of 1 and horizontal offset of 0px
v-enter-active: Represents the time period during which an animation enters, where you can bind the duration of the animation and have some associated animation effects
Exit animation consists of two time points, before (v-leave) and after (v-leave-to)
Flag of completion status: dominated by normal element display
1) Use transition class names (with entries and exits):
(1) HTML structure:
<div id="app"> <input type="button" value="Toggle" @click='flag=!flag'> <!-- <h3 v-show='flag'>This is an element to use animation control</h3> --> <transition> <!-- 1,Use elements to animate transition Wrap up --> <!-- 2,Elements to animate using v-if and v-show To control --> <h3 v-show='flag'>This is an element to use animation control</h3> </transition> </div>
(2) VM instance:
var vm=new Vue({ el:'#app', data:{ flag:false, // Displayed status }, methods:{} });
(3) Define class styles:
.v-enter,.v-leave-to{ opacity: 0; transform: translateX(100px); } /* Transparency 0, offset 40px, use v-enter-to terminate state */ .v-enter-to,.v-leave{ opacity: 0.5; transform: translateX(40px); } .v-enter-active,.v-leave-active{ transition: all 1s ease; } /* Three groups together will appear the phenomenon of one card and one card, the solution is: Define the complete state of the animation */ h3{ /* Defines the completion state, i.e. the termination state, of the animation */ opacity: 0.5; transform: translateX(40px); } /* If v-enter-to and v-leave are undefined styles, the element can be displayed */
2) Use third-party libraries (with access and exit)
(1) Import Animation Class Library:
<link href="https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css" rel="stylesheet">
(2) Define transition s and attributes:
<transition enter-active-class='bounceInDown' leave-active-class="fadeOutDown"> <h3 v-show='flag' class="animated">Ha ha ha ha ha ha ha</h3> <!-- Need to add manually class='animated'Only effective --> </transition>
3) Use the hook function (you can have only half-field animations)
(1) Define the transition component and three hook functions:
<transition @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter"> <div id="ball" v-show='flag'></div> </transition>
(2) Define three methods hook methods:
methods:{ beforeEnter(el){ // Starting state before the ball animation starts el.style.transform = 'translate(0,0)'; }, // The parameter done is a function equivalent to afterEnter() enter(el,done){ // End state after balloon animation el.offsetWidth; // This is fixed writing as long as offset is used. If it is not written, animation cannot be achieved. el.style.transform = 'translate(150px,300px)'; el.style.transition = 'all 1s ease'; // When the animation is complete, the done function is automatically called, which is a reference to the aftreEnter function done(); }, afterEnter(){ // After the balls are animated, do some cleanup this.flag = !this.flag; } } Amount to afterEnter() enter(el,done){ // End state after balloon animation el.offsetWidth; // This is fixed writing as long as offset is used. If it is not written, animation cannot be achieved. el.style.transform = 'translate(150px,300px)'; el.style.transition = 'all 1s ease'; // When the animation is complete, the done function is automatically called, which is a reference to the aftreEnter function done(); }, afterEnter(){ // After the balls are animated, do some cleanup this.flag = !this.flag; } }