This is the 17th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Form field modifier
- Number: converts to a number
- Trim: Remove the opening and closing Spaces
- Lazy: Switches the input event to a change event, which can be triggered when the input is out of focus
<input type="text" v-model.number="number">
<input type="text" v-model.trim="trim">
<input type="text" v-model.lazy="msg">
Copy the code
Example: The element will get focus when the page loads
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
<input v-focus>
Copy the code
3.1 Application Scenarios
Putting too much logic in a template can make the template too heavy and difficult to maintain. A concise example of using computed attributes to make a template more simple: If you want to reverse a string, the processing logic of writing the data in an interpolation can make the template too heavy and difficult to maintain
computed: {
reversedMessage(){
return this.message.split('').reverse().join('')
}
}
<div> {{reversedMessage}}</div>
Copy the code
Calculate the difference between properties and methods
- Computed properties are cached based on their dependencies
- Method does not have a cache
<div>{{reversedMessage}}</div>
<div>{{reversedMessage}}</div>
<div>{{reversedString()}}</div>
<div>{{reversedString()}}</div>
methods: {
reversedString(){
console.log('method')
return this.message.split('').reverse().join('')
}
},
computed: {
reversedMessage(){
console.log('computed')
return this.message.split('').reverse().join('')
}
}
Copy the code
4.1 Usage Scenarios of listeners
Generally used for asynchronous or expensive operations, the properties of watch must be data that already exists in data. The properties of Watch cannot be customized
<input type="text" v-model="lastname"> {{fullname}} watch: { fristname(value) { this.fullname = `${value} ${this.lastname}` }, lastname(value) { this.fullname = `${this.fristname} ${value} ` } }Copy the code
The above example can also be implemented with computational properties
fullname() {
return `${this.fristname} ${this.lastname} `
}
Copy the code
An example of the listener handling asynchrony: The input user name invocation interface verifies that the user user name is available
<span>< span><span>{{tip}}</span> methods: { checkName(usename) { setTimeout (()=>{ this.tip= usename === 'admin' ? },100)}}, watch: {usename(val) {this.checkName(val) this.tip=' checking '}}Copy the code
Format data, such as formatting a string to start with an uppercase letter, formatting a date to a specified format, etc
Define a filter:
Define local filters in a component’s options:
filters: { capitalize: function (value) { if (! value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } }Copy the code
Global definitions
Vue.filter('capitalize', function (value) { if (! value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) new Vue({ })Copy the code
use
<! - in a pair of curly braces - > {{message | capitalize}} <! - in - bind ` ` v -- -- > < div v - bind: id = "rawId | formatId" > < / div >Copy the code
Filters can be connected in series:
{{ message | filterA | filterB }}
Copy the code
Filters are JavaScript functions, so they can take arguments:
{{ message | filterA('arg1', arg2) }}
Copy the code
Example: Format the date in yyy-MM-DD format
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, "d": date.getDate(), "h": date.getHours(), "m": date.getMinutes(), "s": date.getSeconds(), "q": Math.floor((date.getMonth() + 3) / 3), "S": date.getMilliseconds() }; 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; }Copy the code
Parent component passes content to child component:
V-slot details The child component usage remains the same as in the parent component
<template> <child> <! - the default slot - > < template v - slot > < div > default slot < / div > < / template > <! - named slot - > < # template header > < div > named slot < / div > < / template > <! <div> {{slotProps. TestProps}} </div> </template> <child> </template>Copy the code
- Anonymous slot
- A named slot
- Scope slot
- The parent component processes the child component
- The slots of sub-components can be reused and the slot content can be inconsistent
- Using: in a child component template, the element has an expression like props to pass data to the component. MSG =” XXX. A slot can provide a default content, which will be displayed if the parent component does not provide content for the slot. If the parent component provides content for the slot, the default content is replaced
Official Axios documentation
Main features of AXIOS:
- Promise-based HTTP client for browsers and Node.js
- Support for browsers and Node.js
- Intercepts requests and responses
- Automatically convert JSON data
- The ability to transform request and response data usage
axios.get('/user? ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { }));Copy the code
Commonly used API
axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
Copy the code
axios(url[, config])
axios('/user/12345');
Copy the code
The response to a request contains the following information
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
Copy the code
Examples used in the project:
getInfo() { console.log(666) axios({ url: url.getDetailGoodsInfo, method: 'post', data: { goodsId: this.goodsID, }, }) .then((response) => { console.log(response) response.data.code === 200 && response.data.message ? (this.goodsInfo = response.data.message) : Log (this.goodsinfo)}).catch((error) => {console.log(error)})},Copy the code
Configuring default Values
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Copy the code
The interceptor
-
Request interceptor: Sets some information before the request occurs
-
Response interceptors: Do some processing on the data before getting it
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
Copy the code
For class names that are switched during the transition, if you use a nameless
<template>
<div>
<button @click="show = !show">Toggle show</button>
<transition name="bounce">
<p v-if="show">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris facilisis enim libero, at lacinia diam fermentum id. Pellentesque habitant morbi tristique senectus et netus.</p>
</transition>
</div>
</template>
<script>
export default {
data () {
return {
show: true
}
}
}
</script>
<style scoped>
.bounce-enter-active {
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-in .5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
Copy the code