Vue installation
To install scaffolding, use global installation
npm install -g @vue/cli
Copy the code
Run this command to check the Vue CLI version after the installation
vue -V
Copy the code
Initialize a Vue project
vue create lk-demo
Copy the code
And then you get into a whole bunch of options
1. Manually select features 2. Space is selected, A is selected, and the configuration is manualCopy the code
Run the project
npm run serve
Copy the code
Package the project into the dist directory
npm run build
Copy the code
If you only have configuration files, you need to manually install the dependencies to run
npm install
Copy the code
Vue instruction
Double parenthesis expression {{intro}}
- You can directly display the data in data
- You can also perform string operations on the data:
{{intro.toUpperCase()}}
- Note that the double parenthesis expression is written between two labels, which means you can concatenate it with other characters
v-text
- V-text is an attribute. If ni writes other characters between two labels at the same time, the other characters are not displayed
- It’s just plain text, and the data in data will be presented completely
v-html
- The data in data is presented in HTML
v-bind
None of these instructions requires a double parenthesis expression inside a double quotation mark
v-bind:href
- The HTML tag is bound to a property in data:
v-bind:href="site"
- This can be abbreviated as:
:href="site"
v-bind:class
<div :class="oneClass">Style classes can be strings</div>
<div :class="{classOne: true, classTwo: true}">Style classes can be objects</div>
<div :class="['classOne', 'classTwo']">Style classes can be arrays</div>
<div :class="[oneClass, twoClass]">Style classes can be arrays</div>
Copy the code
- If it’s a string, then the quotes are attributes in data
- If it’s an object, the object is the selector in the stylesheet
- If it’s an array, the string in the array is also a selector in the stylesheet
- It’s an array, but it’s not a string, so you can write data in data
v-bind:style
<div
style="width: 300px; height: 200px; margin: 10px auto;"
:style="{backgroundColor: bgColor, fontSize: fSize}">Style classes can be strings</div>
Copy the code
- V-bind :style can also bind styles to elements, but inline styles.
- Note that the attribute name is hump nomenclature, and the attribute is defined in data.
v-on:click
- Bind the element to an event from methods
- You can pass no arguments:
v-on:click="study"
, can also pass parameters@ click = "study (' small liao ')"
- Of course, as you can see, it can be abbreviated:
@click="study"
- After passing the parameter, what is used to receive the parameter? First of all, there must be a parameter in the method, in the method, can be used
${name}
To receive parameters. <button @click="flag = ! Switch flag "> < / button >
@click can be used not only to bind functions, but also to write methods directly inside them.
study(name){
alert(`${name}Wish you success in your studies! `);
}
Copy the code
v-model
- The function of this instruction is to realize a bidirectional binding between the data it binds and the data in data, and communicate with each other in real time.
- Usage:
v-model="msg"
v-if
<div v-if="flag">Class tonight!</div>
<div v-else>No school tonight!</div>
Copy the code
- V-if and v-else that goes with it
- V-if is not hidden by setting the CSS display property
v-show
<div v-show="flag">Tonight on Vue!</div>
<div v-show=! "" flag">No Vue tonight!</div>
Copy the code
- By setting
display: none;
To hide the elements. Therefore, it is a better choice than V-if for frequent show and hide operations.
v-for
Through the array
<ul>
<li v-for="(person, index) in persons" :key="personsKeys[index]">ID: {{personsKeys [index]}}, {{index}}) name: {{person. Name}}, age: {{person. Age}}, gender: {{person. Sex}}</li>
</ul>
Copy the code
- V-for should be used on LI label instead of UL label
- Note that the first argument in parentheses is equivalent to each item in the array and can be used to call the individual data of the object with its contribution
Note: The use of shortid is also involved
-
Install shortid: NPM I shortid –save
-
Import in this component: import shortId from ‘shortId’
-
In data you have personsKeys, which is an empty array
-
To add a Mounted mount point, call shortid to automatically generate a random number as the ID
mounted() {
this.personsKeys = this.persons.map(v= >shortId.generate())
}
Copy the code
- It can then be used as in the code section above
- V-for may be needed
:key
This property, otherwise the console may warn
Traverse object
<ul>
<li v-for="(item, key) in persons[0]">
{{key}} --- {{item}}
</li>
</ul>
Copy the code
- Key is the key of the object
- Item corresponds to the value of the object
Other instructions
v-pre
<p v-pre>{{intro}}</p>
Copy the code
- It seems that when this property is added, the double brace expression is not parsed and instead displayed as plain text on the page.
- It doesn’t need arguments
v-cloak
<p v-cloak>{{message}}</p>
Copy the code
- When the Vue is a bit slow to load, it may be presented as source code, such as the v-cloak expression here, to avoid the flicker problem.
v-once
<p v-once>{{name}}</p>
Copy the code
- It causes the double parenthesis expression to be parsed only once and then not updated even if the data in the data is changed by the V-model
The use of the ref
<p ref="fish">I'm a fish</p>
Copy the code
- It’s not an instruction, it’s a quote or something. Ref is used to register references to elements or subcomponents. The reference information will be registered with the parent component’s $refs object. If used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component.
- You can kind of view it as an ID attribute, where you get that element and then you can do something with it.
- If you want to output its contents, you can do so. Notice that innerHTML is only printed here
The HTML content in the middle of the tag
console.log(this.$refs.fish.innerHTML);
Copy the code
Custom global and local directives
Custom global directives
Vue.directive('upper-word', (el, binding)=>{
console.log(el, binding);
el.textContent = binding.value.toUpperCase();
});
Copy the code
- Global directives need to be written in main.js
- All Vue instructions need to be preceded by one
v-
Custom local directives
directives: {
'lower-word'(el, binding){
console.log(el, binding); el.textContent = binding.value.toLowerCase(); }}Copy the code
- Local directives are defined using
directives
This hook option - Note that this is slightly different from the global directive definition.
Calculate attribute
- Computed properties, like data in data, can be bound using v-Models
- Compute properties have both
set()
andget()
Method,get()
Used to calculate the data in data,set()
Used to assign data obtained from it to data in data
fullNameTwo: {
get(){
// console.log(' called the getter for fullNameTwo ');
return this.firstName + ', ' + this.lastName;
},
set(value){
// console.log(' called setter for fullNameTwo, value: ${value} ');
// update firstName and lastName
let names = value.split(', ');
console.log(names);
this.firstName = names[0];
this.lastName = names[1]; }}Copy the code
Data to monitorwatch
/ / configuration watch
watch: {
/ / to monitor firstName
firstName(value){
console.log('Watch' detects firstName change:${value}`);
/ / update the fullNameThree
this.fullNameThree = value + ', ' + this.lastName;
},
/ / to monitor the lastName
lastName(value){
console.log('Watch watches lastName change:${value}`);
/ / update the fullNameThree
this.fullNameThree = this.firstName + ', '+ value; }}Copy the code
- Watch is the same level as data and computed, and can be used to monitor data in data.
- Each function in Watch has the same name as the property in data, which is automatically called when the property is changed.
- The method can also internally perform operations on data in data.
The event processing
The event object
<button @click="ClickBtn (' clickBtn ', $event)>Am I</button>
Copy the code
- You can fire an event and pass both the parameters and the event object, which has many, many time-dependent properties
Event modifier@click.prevent
<a href="http://www.itlike.com" @click.prevent="aClick">Liao class</a>
Copy the code
- Its presence prevents the default behavior of the element.
- For example, the link above is a hyperlink, but now clicking on it does not jump to the link. Instead, aClick() is performed
- In the case of a form, auto-commit methods are also blocked.
Event modifier@click.stop
<div style="width: 100px; height: 100px; background-color:red;" @click="divClick">
<button @click.stop="btnClick">Am I</button>
</div>
Copy the code
- This modifier is used on child element tags to prevent events from bubbling. That is, clicking on the child element’s label does not trigger an event on the parent element.
Key modifier
<input type="text" @keyup.enter="dealKey">
Copy the code
dealKey(event){
console.log(event);
console.log(event['keyCode']);
}
Copy the code
- Using @keyUp, you can follow up a variety of keys, meaning that the event is executed when pressed and released.
- It can also be passed in the object that triggered the event
event['keyCode']
Gets the ASCII code of the key
The filter
Global filter
Vue.filter('wholeMoneyFormat', (value)=>{
return 'selections' + Number(value).toFixed(4);
});
Copy the code
<p>{{money | wholeMoneyFormat}}</p>
Copy the code
- Global filters need to be written in main.js, as shown in the code above
- The filter above means: convert the passed parameter to a number with four decimal places, then prefix it with a yuan symbol and return it.
- You need to use a double parenthesis expression, the first is the parameter to filter, the second filter name, separated by a vertical line.
Local filter
filters: {
moneyFormat(value){
return 'selections' + Number(value).toFixed(2);
},
timeFormat(value, format='YYYY-MM-DD HH:mm:ss') {returnmoment(value).format(format); }}Copy the code
- Local filters are defined as shown in the code above. The use of global filters is exactly the same
- The first money filter converts the passed argument to a number with two decimal digits and is preceded by a yuan symbol.
- The second time filter uses the moment plug-in to convert the events in value to the time format in format. Of course, you can also manually change the filtering time format at the time of the call.
<p>{{time | timeFormat('YYYY-MM-DD')}}</p>
Copy the code
Vue transitions and animations
Only use the class
<button @click="show = ! show">switch</button>
<transition name="fade">
<div class="box" v-if="show">Liao class college</div>
</transition>
Copy the code
- To use animation in Vue, you need to use the Transition tag, which must have a name attribute
- We can toggle the animation when the element appears and disappears by setting a V-if
- Then write the end style and the ongoing style in the style sheet. The selector name needs to use the name attribute mentioned above, for example:
.fade-enter
..fade-leave-to
..fade-enter-active
..fade-leave-active
- Here is an example of CSS
.fade-enter..fade-leave-to{
opacity: 0;
transform: translateX(200px) scale(3);
}
.fade-enter-active..fade-leave-active{
transition: all 2s ease-in-out;
}
Copy the code
use@keyframes
- Note: if the image is imported using: SRC, you need to import the image first
import pic from '@/assets/img_02.jpg'
, and then treat it as a piece of data in data - Two CSS classes, the first representing the animation on entry and its duration. The second animation represents the vanishing animation and its duration, and shows the reverse of the first animation.
- The detailed code is as follows
<button @click="flag = ! flag">switch</button>
<p></p>
<transition name="bounce">
<img v-if="flag" :src="pic" alt="">
</transition>
Copy the code
.bounce-enter-active {
animation: bounce 1s;
}
.bounce-leave-active {
animation: bounce 1s reverse;
}
@keyframes bounce {
0% {
transform: scale(0); 25%} {transform: scale(0.2); 50%} {transform: scale(0.4); 75%} {transform: scale(0.6); 100%} {transform: scale(1); }}Copy the code
Import an external animated CSS library
<button @click="flag = ! flag">switch</button>
<p></p>
<transition
enter-active-class="animated rollIn"
leave-active-class="animated rollOut"
:duration="{ enter: 1000, leave: 500 }"
>
<img v-if="flag" :src="pic" alt="">
</transition>
Copy the code
- The animation library is used in the code above
- Install the animate. CSS:
npm i animate.css --save
- Then import
animate.css
:import animate from 'animate.css'
- The three properties in Transition represent the animation of the entry, the animation of the disappearance, and the duration of the entry and disappearance.
The life cycle
- The Vue lifecycle is in order:
beforeCreate
,created
,beforeMount
,mounted
,beforeUpdate
,updated
,beforeDestroy
,destroyed
- Typically, the first four life cycles are invoked in quick succession as soon as the component is enabled.
- It is then called each time the data in data is modified
beforeUpdate
,updated
Two methods - Finally, if you want to enter the destruction lifecycle, you need to actively trigger this method in the code below
- Also, if the timer is in its life cycle, note that it is asynchronous, and the timer may still be working even after it has been destroyed. This is a good time to set up a clear timer during the destruction lifecycle.
destory(){
this.$destroy();
}
Copy the code
Component communication
The child tells the parent that I triggered a method
The parent component
- App.vue needs to bind events to components
- Write events in methods
<CustomEvents @btnClick="deleteP"/>
Copy the code
deleteP(args){
console.log(args);
this.$refs.word.remove();
}
Copy the code
Child components
- The child component also needs to bind events to an element
- But instead of processing the event itself, you tell the parent element, which event did you trigger, and what were the parameters
btnClick(){
// Tell the parent that I clicked the button
this.$emit('btnClick', {name: 'Hahaha'.sex:'male'});
// TODO
}
Copy the code
Parent component passes data and methods to child component: props
<PropsComponent :age=25 :person="p" :log-person="logPerson" />
Copy the code
props: { name: String, age: Number, person: Object, logPerson: Function } */ props: { name: {type: String, required: True, default: 'hold '}, age: {type: Number, required: true, default: 20}, person: Object, logPerson: Function}Copy the code
- The parent component writes on the component
:age
To pass data and methods to the child components. The data and methods are already defined in the parent component - The child component needs to receive data and methods from the parent through the props hook option
- The child components can then use the parent’s data and methods as if they were their own
Custom events
- Sent from the child to the parent, function name, function parameters
this.$emit('addTodo', todo);
- The parent component needs to listen on this component:
<Header ref="header"/>
- Then bind a custom event listener to the parent component:
this.$refs.header.$on('addTodo', this.addTodo);
Notice that this is written inmounted
In this hook option; Then, instead of writing () to take the argument, this writing will automatically pass the todo argument
Publish and subscribe model
- Install pubSub plugin:
npm install --save pubsub-js
- Introduce pubsub-js in app. vue and item:
import PubSub from 'pubsub-js'
Anyway, where you need to publish, subscribe, need to import - Child component publishes messages:
PubSub.publish('delTodo', this.index)
- The parent component receives the message. Here’s the code. Mounted: The token argument is passed by the child component
PubSub.subscribe('delTodo', (msg, token)=>{
// console.log(msg, token);
this.delTodo(token);
});
Copy the code
slot
<label>
<slot name="isCheck"></slot>
</label>
<span>
<slot name="finish"></slot>
</span>
<slot name="delete"></slot>
Copy the code
<Footer>
<input slot="isCheck" type="checkbox" v-model="isCheck"/>
<span slot="finish">Completed {{finishedCount}} piece/total {{todos.length}} piece</span>
<button slot="delete" class="btn btn-warning" @click="delFinishedTodos">Clear completed tasks</button>
</Footer>
Copy the code
- You don’t have to write your own code in the footer, you just leave the slots out. You’re using a tag, so you have to have a name attribute.
- The parent component inserts directly into the child component
- This allows you to call methods and evaluate properties directly from the parent component
Vuex
- Installation:
vue add vuex
Vue router
Vue-router basic use
- Install: NPM install vue-router –save
- Create the router.js file
- Introduced in main.js and placed in an instance of Vue
- Create a view page and configure route navigation and route egress in app. vue
router.js
import Vue from 'vue'
import Router from 'vue-router'
// Import the page
import Home from './views/Home'
import About from './views/About'
Vue.use(Router);
export default new Router({
// history mode is no #
// mode: 'history',
routes: [
{ path: '/'.redirect: '/home' },
// Redirect to a named route where name is the route name
// { path: '/', redirect: {name: 'about'} },
// This uses a method to redirect to the destination route
// { path: '/', redirect: to => { return '/home'}},
// The name attribute is just the name of the route
{path: '/home'.name: 'home'.component: Home},
{path: '/about'.name: 'about'.component: About},
]
})
Copy the code
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false;
new Vue({
router,
render: h= > h(App),
}).$mount('#app');
Copy the code
Configure route navigation and route egress in app. vue
<! -- Set route navigation -->
<div id="nav">
<router-link to="/home">Home page</router-link>
<router-link to="/about">about</router-link>
</div>
<! -- Set routing egress -->
<router-view></router-view>
Copy the code
Route history and Hash mode
Obtaining Route Parameters
import Vue from 'vue'
import Router from 'vue-router'
// Import the page
import Home from './views/Home'
import About from './views/About'
import Mine from './views/Mine'
Vue.use(Router);
/* let func = ({params, query})=>{ return { name: params.name, sex: params.sex, height: query.height, dog: query.dog, } }; * /
let func = (route) = >{
return {
name: route.params.name,
sex: route.params.sex,
height: route.query.height,
dog: route.query.dog,
}
};
export default new Router({
routes: [{path: '/'.redirect: '/home' },
{path: '/home'.name: 'home'.component: Home},
{path: '/about'.name: 'about'.component: About},
// {path: '/mine/:name/:sex', name: 'mine', component: Mine}
/ / {path: '/ mime, name:' mine ', component: mime, props: {name: 'small liao'}}
// {path: '/mine/:name/:sex', name: 'mine', component: Mine, props: true}
{path: '/mine/:name/:sex'.name: 'mine'.component: Mine, props: func}
]
})
Copy the code
Mine.vue
<template>
<div id="mine">
<h2>Personal center</h2>
<p>------------------------------------------</p>
<h2>Path parameters obtained based on the routing object</h2>
<p>Name: {{$route. Params. Name}}</p>
<p>Gender: {{$route. Params. Sex}}</p>
<p>Height: {{$route. Query. Height}}</p>
<p>Dog: {{$route. Query. Dog}}</p>
<h2>Path parameters obtained from the property object</h2>
<p>Name: {{name}}</p>
<p>Gender: {{sex}}</p>
<p>Height: {{height}}</p>
<p>Dog: {{dog}}</p>
</div>
</template>
<script>
export default {
name: "Mine".props: ['name'.'sex'.'height'.'dog'],
created() {
console.log(this.$route);
/* console.log(this.$route); console.log(this.$route.path); console.log(this.$route.params); console.log(this.$route.query); * /
// console.log(this.$router);}}</script>
<style scoped>
#mine{
width: 300px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
h2{
color: green;
}
</style>
Copy the code
- The code for getting route parameters is above
- When WE say get route parameters, we mean that the data is on the link, and we need to get that data in some way
- There are several ways to pass parameters through routing:
{path: '/mine/:name/:sex', name: 'mine', component: Mine}
By writing colons on the route{path: '/mine', name: 'mine', Component: mine, props: {name: 'props '}}
In this component, write the props hook option and the variable names for the data{path: '/mine/:name/:sex', name: 'mine', component: Mine, props: true}
To obtain data in the above two ways{path: '/mine/:name/:sex', name: 'mine', component: Mine, props: func}
Pass data by address and method
Embedded routines by
import Vue from 'vue'
import Router from 'vue-router'
// First level interface
import Home from './views/Home'
import About from './views/About'
import Mine from './views/Mine'
// Secondary interface
import News from './views/News'
import Shop from './views/Shop'
Vue.use(Router);
export default new Router({
routes: [{path: '/'.redirect: '/home' },
{
path: '/home'.name: 'home'.component: Home,
children: [{path: '/home'.redirect: '/home/news' },
{path: 'news'.name: 'news'.component: News},
{path: 'shop'.name: 'shop'.component: Shop},
]
},
{path: '/about'.name: 'about'.component: About},
{path: '/mine'.name: 'mine'.component: Mine}
]
})
Copy the code
- The so-called nested routine is a slash followed by a slash
- Nested configuration files are not different from other files, mainly router.js
- Note the configuration of nested routes: child routes do not need to be preceded by /
Global route front and back guards
import Vue from 'vue'
import Router from 'vue-router'
// First level interface
import Login from './views/Login'
import DashBoard from './views/DashBoard'
// Secondary interface
import Home from './views/Home'
// import About from './views/About'
import Mine from './views/Mine'
const About = (a)= > import('./views/About');
Vue.use(Router);
const router = new Router({
routes: [{path: '/'.redirect: '/dashboard' },
{
path: '/dashboard'.name: 'dashboard'.component: DashBoard,
children: [{path: '/dashboard'.redirect: '/dashboard/home' },
{path: 'home'.name: 'home'.component: Home,},
{path: 'about'.name: 'about'.component: About},
{path: 'mine'.name: 'mine'.component: Mine}
],
},
{path: '/login'.name: 'login'.component: Login}
]
});
// Global route front-guard
router.beforeEach((to, from, next) = >{
// console.log(to, from);
if(to.path ! = ='/login') {// Verify login
if(window.isLogin){ // Already logged in
next();
}else { // No login
// Upload the address you want to go to to the login page, so that you can be redirected to the page immediately after successful login
// next('/login? redirect='+ to.path);
// next('/login? redirect=/dashboard/mine');
next('/login'); }}else { // No validation is required
next();
}
/ / release
next();
});
// Global route post guard
router.afterEach((to, from) = > {
// console.log(' Here we go! ');
});
export default router;
Copy the code
- Mainly through the front guard to control when the user can enter the page
- If the user accesses the login page, the system directly permits the login without checking
- If the user logs in to another page, check whether the user logs in. If the user does not log in to the login page, check whether the user has logged in to the login page
- All other conditions will be released
mine.vue
export default {
name: "Mine",
beforeRouteEnter(to, from, next){
console.log('Call before entry');
next();
},
beforeRouteUpdate(to, from, next){
console.log('Route parameters have changed');
next();
},
beforeRouteLeave(to, from, next){
console.log('Call before route leaves'); next(); }}Copy the code
There are several lifecycle hook options that are called before entering the component, when route parameters change, and when the route leaves
login.vue
<template> <div> <h2> <button @click="login"> </button> </div> </template> <script> export default {name: "Login", methods: { login(){ // 1. Window. isLogin = true; Const redirect = this.$route.query. Redirect; If (redirect){// This.$router. Push (redirect); $router. Replace ('/'); $router. Replace ('/'); } } } } </script> <style scoped> </style>Copy the code
- The login page is responsible for login related transactions
- When the user clicks the login button, first set the global isLogin to true
- Gets the callback address of the user, if there is a callback address directly to; If not, head to the home page
Data localization
- Hand write a tool class
- Import the utility class in app.vue
- The data in data needs to be read from localStorage and stored to localStorage when any toDOS data changes
Utility class
const LK_TODO = 'lk_todo';
export default {
readTodos(){
return JSON.parse(localStorage.getItem(LK_TODO) || '[]');
},
saveTodos(todos){
console.log(todos);
localStorage.setItem(LK_TODO, JSON.stringify(todos)); }}Copy the code
- To use localStorage, you need to pass a key, either to read or to fetch. Note that this is only an array, so a string constant is used as the key
- The first method that reads the data has internal
| | '[]'
In order to be able to read data in any case, even if it’s an empty array
Read the data
todos: localStorageUtil.readTodos()
Copy the code
Take the data
watch: {
// Deep monitoring
todos: {
handler: localStorageUtil.saveTodos,
deep: true.// Deep monitoring
// immediate: true}}Copy the code
- Fetching data requires depth monitoring, because arrays contain objects, and only depth monitoring can listen for changes in the properties of objects in arrays.
- Immediate If true, the handler method is executed immediately upon initialization; otherwise, the handler method is executed when todos changes.
UI framework
elementUI
- Element documentation: element.eleme.cn/#/zh-CN/com…
- Installation:
npm i element-ui -S
- Add UI library to Vue:
vue add element
- Fully import, N, CN
vue ui
: Use visual panels to manage projects (usually not)
After the above steps, plugins/element.js are automatically integrated and imported into main.js. It can then be used directly in app.vue.
- Copy the HTML code into the template
- Copy the data part of the script code into app.vue. Note that the code structure here is exactly the same as vue.
VantUI
- Documents: youzan. Making. IO/vant / # / useful – C…
- Installation:
npm i vant -S
- Configuration is loaded on demand, introducing Babel:
npm i babel-plugin-import -D
- Configure babel.config.js, which can be copied and pasted from the document
- Import the required components from main.js, or make a separate JS file and import them via import
Configure the Babel. Config. Js
module.exports = {
presets: [
'@vue/app'].plugins: [['import', {
libraryName: 'vant'.libraryDirectory: 'es'.style: true
}, 'vant']]};Copy the code
Import the required components in main.js
import { Button } from 'vant';
Vue.use(Button);
import { Cell, CellGroup } from 'vant';
Vue.use(Cell).use(CellGroup);
import { DatetimePicker } from 'vant';
Vue.use(DatetimePicker);
Copy the code
Plug-in installation and use
shortid
<ul>
<li v-for="(person, index) in persons" :key="personsKeys[index]">ID: {{personsKeys [index]}}, {{index}}) name: {{person. Name}}, age: {{person. Age}}, gender: {{person. Sex}}</li>
</ul>
Copy the code
- The installation
shortid
:npm i shortid --save
- Import in this component:
import shortId from 'shortid'
- In data
personsKeys
This data, it’s an empty array - To add a Mounted mount point, call shortid to automatically generate a random number as the ID
mounted() {
this.personsKeys = this.persons.map(v= >shortId.generate())
}
Copy the code
- It can then be used as in the code section above
- V-for may be needed
:key
This property, otherwise the console may warn
moment
- Installation:
npm i moment --save
- Use: Note that the use of any plug-in needs to be imported inside the component first
import moment from 'moment'
. You can then use the plug-in as if it were a function
Case summary
V-for sort small case
- The data comes from the data that has been defined in the data
- The V-for is used the same way we did when we iterated through the array, again using Shortid, but instead of displaying shortid on the page, we add 1 to the index
- The in in v-for is a sorted array that was computed using properties
- Sorting by default, ascending or descending by age, is distinguished by passing different parameters to the calculated properties.
- The code for sorting is as follows. Note that the following arrays need to be filtered and then sorted by criteria
computed: {
filterPersons() {
// 1. Obtain data
let {searchName, persons, orderType} = this;
// 2. Fetch the data from the array
let arr = [...persons];
// 3. Filter array
if (searchName.trim()) {
arr = persons.filter(p= >p.name.indexOf(searchName) ! = =- 1);
}
/ / 4. Sort
if (orderType) {
arr.sort((p1, p2) = > {
if (orderType === 1) { / / descending
return p2.age - p1.age
} else { / / ascending
return p1.age - p2.age
}
});
}
returnarr; }},Copy the code
Form add and delete small case
- Data contains existing data and a new empty object object that can set some default values
- Each input tag sets the V-Model, bound to each property in the empty object
- When adding data: first use destruct assignment to get the input box data from the object; The data is then validated, for example, that it cannot be null; Insert data directly using the array unshift method; Finally, remember to empty the empty object and restore it to its default value
- When you hit the delete button, you simply call the splice method with the index as the first argument and the index as the second argument to delete several elements from the index position
todoList
First edition todoList
Header
- The main task of the Header is to add new tasks to todoList, and the main method is to add todo
- The method is implemented in app.vue and then used
:addTodo="addTodo"
To pass its own methods to child components. Of course the sub component needs to accept using props. - The child component is responsible for only one data title, and since the task cannot be completed when it is created, the finished check box is set to false by default.
- The child component still needs some other operations: ① To determine whether the user entered an empty string; (2) A toDO is concatenated based on user input, which consists of title and FINISHED data. ③ call the add method of the parent component; ④ clear title data
List
- (1) When the mouse moves over a todo, the background color of the todo turns gray and the delete button is displayed
- App.vue needs to pass toDOS data to the List and a method to delete a particular TODO
- The List uses props to receive todos and delete methods. Then v-for is used to traverse toDOS. Of course, each item traversed is its child component. List needs to pass item its data TODO, the index of the TODO in ToDOS, and the method to delete the TODO
- The child child component item first needs to receive two pieces of data and a method passed from above.
- The delete button appears when the mouse cursor is moved over item and the background color change is passed
@mouseenter
,@mouseleave
Two ways of firing events, each passed to the same eventtrue
,false
Two different parameters. - Background color is set
:style
Use a value in data, so that you can use methods to change the data property to adjust the background color - The button is shown and hidden using v-show, which is also a data control of true or false in data, so we can set this property to true in the method to make the button appear
- Delete the todo and use the method in the parent component
Footer
- Footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer footer ② : all; ③ : Click the delete Finished button.
- Selecting all toDos and deleting completed toDos are defined in app.vue. Both methods, along with the toDOS data, are then passed to the Footer component
- One of the most important features in footer is to know how many toDos have been completed. This is done by counting properties. See the code below. The array reduce method is used, which is essentially a +1 count operation.
- One of the most important functions in footer is to select all, that is, when all of the above is selected, it should also be selected, if it is selected, all of the above should be selected. This is done by setting a V-Model to the checkbox and binding a calculated property.
- Where get() processes the first one, and the judgment condition is that the number of toDos completed is equal to the length of todos, and the length is not 0.
- Set () handles the second, which calls the parent component’s all-select method with the current value of the evaluated property, true, and false. The parent component’s all-select method walks through todos, setting all of its FINISHED properties as parameters. Note that the trick here is that the footer all button is bound to the V-Model so that the set() parameter is true.
- Finally, it is easy to delete all completed toDos without passing any arguments and simply call the parent component’s methods.
finishedCount(){
return this.todos.reduce((total, todo) = > total + (todo.finished ? 1 : 0), 0);
},
Copy the code