Basic instruction of vue - 1
v-for
The v-for instruction renders a list based on an array, which is similar to the traversal syntax of JavaScript
v-for="item in list"
list is an array, and item is the array element currently traversed
v-for="(item,index) in list" where index is the index of the current cycle, and the subscript starts from 0
<div id="app"> <table> <tr class="thead"> <td>Serial number</td> <td>full name</td> <td>Age</td> </tr> <tr v-for="(item,index) in list"> <td v-text="index+1"></td> <td v-text="item.name"></td> <td v-text="item.age"></td> </tr> </table> </div> var vm = new Vue({ el: '#app', data: { list:[{ name:'Zhang San', age:18 },{ name:'Li Si', age:23 }] } })
v-bind
V-bind dynamically binds one or more features. You can take a parameter after its name, separated by a colon in the middle. This parameter is usually the attribute of HTML elements, such as v-bind: class
Class can exist at the same time as v-bind:class, that is to say, if there is a class, adding v-bind:class will not overwrite the original style class, but add a new class name based on the original one
<div id="app"> <img v-bind:src="img" class="logo" v-bind:class="isLogo?'':'product'" v-bind:style="{'border':hasBorder?'2px solid red':''}"></img> </div> var vm = new Vue({ el: '#app', data: { img:'https://www.baidu.com/img/bd_logo1.png', isLogo:false, hasBorder:true } })
v-if
v-if is a conditional rendering instruction, which deletes and inserts elements according to the authenticity of the expression
Basic syntax:
v-if="variable"
variable is an expression that returns a Boolean value. The expression can be a Boolean attribute or an expression that returns a Boolean.
<div id="app"> <div v-if="isMale">man</div> <div v-if="age>=20">age:{{age}}</div> </div> var vm = new Vue({ el: '#app', data: { age:25, isMale:true, } })
v-show
The v-show instruction determines whether an element is displayed or hidden by changing the css attribute (display) of the element.
The difference between v-if and v-show
v-show will render html regardless of whether the condition is true or not, while v-if will render only if the condition is true
v-model
<div id="app"> <p>{{ message }}</p> <input type="text" v-model="message"/> </div>
Bind message to the text box. When the value of the text box is changed, the content in < p > {{message} < / P > will also be updated.
Conversely, if you change the value of message, the value of the text box will also be updated
v-on
It is used to listen for DOM events. The usage is similar to v-bind. It can be replaced by @ instead
<button @click="show">
Various pits in vue - 2
ie compatibility of vue
For ie browser, vue can only support ie9 and above at least.
In addition, route jump of Vue router is not supported ---- this$ router. The push method can only use the window of native JavaScript Localization or window Open these methods.
vue compatibility with apple phones
vue is still very friendly for Apple compatibility, but for the native JavaScript window The open syntax will have a security mechanism. In order to achieve compatibility, you can use window localtion. Href, or find a way to skip this security mechanism
code:
Open an empty window before the callback code, such as var w = window open(xxx); Then set its location in the callback function.
var openWin = function(){ var winRef = window.open("url","_blank"); $.ajax({ type: '', url: '', data: '', ...... success:function(json){ winRef.location = "new url"; } }); };
Identification of mobile phone system by vue
In order to make a system compatible with both pc and mobile phones, this model judgment must be added.
// Judge model appSource() { const u = navigator.userAgent; const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); if (isiOS) { this.PhoneStatus = true; // If it's ios, do it } else { this.PhoneStatus = false; // Or Android or pc } },
Detection browser version of vue
vue is not suitable for ie8 or below, so a detection prompt is given, and the following code must be placed in the index. Of the public folder HTML.
code:
if(navigator.appName == "Microsoft Internet Explorer"&&parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE",""))<9){ alert("Yours IE The version is too low. Please report it for normal use IT Operation and maintenance upgrade IE!"); }
Some extensions of vue -- 3
Password encryption of vue
This is agreed with the back end. Generally, the password is encrypted for login verification.
We need to introduce some third-party packages -- crypto js
Usage:
1. Use first
npm install cypto-js
-
Create crypto JS file
import CryptoJS from 'crypto-js/crypto-js' // Default KEY and iv if not given let KEY = CryptoJS.enc.Utf8.parse("aes@032sA33#$aQk"); let IV = CryptoJS.enc.Utf8.parse('_aes_secret_iv__'); /** * AES IV: basekey returns the encrypted string */ export function Encrypt(word, keyStr, ivStr) { let key = KEY let iv = IV if (keyStr) { key = CryptoJS.enc.Utf8.parse(keyStr); iv = CryptoJS.enc.Utf8.parse(ivStr); } let srcs = CryptoJS.enc.Utf8.parse(word); var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding }); // console.log("-=-=-=-", encrypted.ciphertext) return CryptoJS.enc.Base64.stringify(encrypted.ciphertext); } /** * AES Decryption: string key iv returns base64 * */ export function Decrypt(word, keyStr, ivStr) { let key = KEY let iv = IV if (keyStr) { key = CryptoJS.enc.Utf8.parse(keyStr); iv = CryptoJS.enc.Utf8.parse(ivStr); } let base64 = CryptoJS.enc.Base64.parse(word); let src = CryptoJS.enc.Base64.stringify(base64); var decrypt = CryptoJS.AES.decrypt(src, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding }); var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8); return decryptedStr.toString(); }
-
Import in the vue file used
import {Encrypt} from "@/utils/crypto.js";
Custom components of vue
Determine the component type, whether it is a child component or a parent component.
Analyze the specific functional logic of components and the changes of css.
For example: search component, which is a sub component, has two cases: focus and out of focus.
There are two boxes, one is the search box and the other is the display box. The display box corresponds to the state of focus and defocus. There will also be style changes.
Code specification of vue
When vue builds a page, it's best to annotate the name of each module
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-PP2aLSjP-1619311117044)(./1.png)]
vue's method is to write down each step process and what it is specifically to achieve. You can write down the functional steps you want to achieve and write them step by step before the implementation of this method.
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-Gqfdv5Nt-1619311117046)(./2.png)]
In addition to using promise objects, you can use async/await mode to handle asynchronous functions
async getUser () { const res = await GetUser() console.log(res) } // GetUser() is an encapsulated api interface that directly calls the return object.
async/await has no advantage if it is just a single promise object.
However, when using promise in a promise, the advantage of using async/await is obvious.
This is promise:
collectOrCanel (item) { checkToken().then(res=>{ if(res.data.code !== 200){ this.$router.push({path:'/login'}) }else{ console.log(item) // The parameters for judging whether they are collected and passed are different if(item.collectFlag == false){ //Not collected let collectFlag = "collect" Collect(collectFlag,item.sysid,item.systype).then(result => { this.sysList=[] // Refresh List this.getList() }).catch(err=>{console.log(err)}) }else if(item.collectFlag == true){ // Collected let collectFlag = "decollect" Collect(collectFlag,item.sysid,item.systype).then(result => { this.sysList=[] // Refresh List this.getList() }).catch(err=>{console.log(err)}) } } }).catch(err => { console.log(err) }) },
This is async/await
async collectOrCanel (item) { const res = await checkToken() if(res.data.code !==200 ){ this.$router.push({path:'/login'}) }else { if(item.collectFlag == false){ let collectFlag = "collect" const result = Collect(collectFlag,item.sysid,item.systype) this.sysList = [] this.getList() }else if(item.collecFlag == true){ let collectFlag = "decollect" const result = Collect(collectFlag,item.sysid,item.systype) this.sysList = [] this.getList() } } }
Request encapsulation specification of vue
Package and configure three files
.env. Test ==================> test environment configuration
NODE_ENV = 'production' VUE_APP_MODE = 'test' VUE_APP_API_URL=https:// outputDir = test
.env. Production ===========> production environment
NODE_ENV = 'production' VUE_APP_MODE = 'production' VUE_APP_API_URL=https:// outputDir = production
. env ================== > development environment
NODE_ENV = 'development' VUE_APP_MODE = 'development' VUE_APP_API_URL=https://36.1.44.66:443
Then in package json
"scripts": { "serve": "vue-cli-service serve --mode development", "build": "vue-cli-service build --mode test && vue-cli-service build --mode prod", "test": "vue-cli-service build --mode test", "prod": "vue-cli-service build --mode prod", "lint": "vue-cli-service lint", "inspect": "vue-cli-service inspect" },
Finally, in the js file of api
myaxios.defaults.baseURL = process.env.VUE_APP_API_URL
Just set the interface base address of axios to a variable in the configuration file.
Adaptive control of vue
1. Implementation principle and operation environment
Implementation principle: when vue is compiled, the px unit of css is modified to rem to realize screen adaptation
vue/cli version 4.5.6
Amfe flexible version 2.2.1
Postcss loader version 4.1.0
postcss-px2rem version 0.3.0
2. Install amfe flexible module
npm i -S amfe-flexible
3. Install postcss-px2rem
npm install -D postcss-loader
npm install -D postcss-px2rem
4. In main JS introduces amfe flexible
import 'amfe-flexible'
5. Configure Vue config. js
css: {
//css preset configuration item
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 128, / / width of design drawing / 10 for example, if your design drawing is 1920, here you will 1920 / 10 = 192
remPrecision: 8 / / how many decimal places are reserved for the converted rem
})
]
}
}
},
Note: set remUnit according to the actual project. For example, your design drawing is 1920 wide. Here, you will have 1920 / 10 = 192
pm install -D postcss-px2rem
4. In main JS introduces amfe flexible
import 'amfe-flexible'
5. Configure Vue config. js
css: {
//css preset configuration item
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 128, / / width of design drawing / 10 for example, if your design drawing is 1920, here you will 1920 / 10 = 192
remPrecision: 8 / / how many decimal places are reserved for the converted rem
})
]
}
}
},
Note: set remUnit according to the actual project. For example, your design drawing is 1920 wide. Here, you will have 1920 / 10 = 192