key attribute Why add
key -- api explanation
The special attributes of key are mainly used in the virtual dom algorithm of vue. If key is not applicable, vue will use an algorithm to minimize dynamic elements and try to repair / reuse the same type of elements as much as possible. With key, it rearranges the order of elements based on the change of key, and removes the elements that key does not exist.
Why do v-for add Key
<div id="app"> <div> <input type="text" v-model="name"> <button @click="add">Add to</button> </div> <ul> <li v-for="(item, i) in list"> <input type="checkbox"> {{item.name}} </li> </ul> <script> // Create a vue instance to get the viewmodel var vm = new Vue({ el: '#app', data: { name: '', newId: 3, list: [ {id:1,name''} ] }, methods: { add() { this.list.unshift({ id: ++this.newId, name: this.name }) this.name="" } } }); </script> </div>
There are key
<div id="app"> <div> <input type="text" v-model="name"> <button @click="add">Add to</button> </div> <ul> <li v-for="(item, i) in list" :key="item.id"> <input type="checkbox"> {{item.name}} </li> </ul> <script> // Create Vue instance to get ViewModel var vm = new Vue({ el: '#app', data: { name: '', newId: 3, list: [ { id: 1, name: '' }, { id: 2, name: '' }, { id: 3, name: '' } ] }, methods: { add() { //Notice that this is unshift this.list.unshift({ id: ++this.newId, name: this.name }) this.name = '' } } }); </script> </div>
Why do I have to add a unique key when I use v-for?
const list = [ { id: 1, name: 'test1', }, { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, ]
<div v-for="(item, index) in list" :key="index" >{{item.name}}</div>
const list = [ { id: 1, name: 'test1', }, { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, { id: 4, name: 'I'm the last piece of data to add', }, ]
const list = [ { id: 1, name: 'test1', }, { id: 4, name: 'I'm the data of the queue', } { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, ]
Two identical components produce similar dom structure, and different components produce different dom structure.
A group of nodes at the same level
Special characteristics key
Expected: number | string
The special attribute of key is mainly used in the virtual dom algorithm of vue to identify vnodes when comparing new and old nodes.
<ul> <li v-for="item in items" :key="item.id"></li> </ul>
It can be used to force replacement of elements, components, rather than reuse it.
Trigger the lifecycle hook of the component completely Trigger transition
<transition> <span :key="text">{{text}}</span> </transition>
ref is used to register reference information for an element or child component, which will be registered on the $refs object of the parent component. If it is used on a normal dom element, the reference point is the dom element. If it is used on a subcomponent, the reference points to the component instance:
<p ref="p"> hello </p> <child-component ref="child"></child-component>
When v-for is used for an element or component, the reference information will contain an array of dom nodes or component instances
is For dynamic components and works based on the limitations of templates within the dom
<component v-bind:is="currentView"></compoent> <table> <tr is="my-row"></tr> </table>
data: function () { return { todos: [ { id: 1, text: 'Learning and using v-for' }, { id: 2, text: 'Learning and using key' } ] } }
<ul> <li v-for="todo in todos"> {{ todo.text }} </li> </ul>
<ul> <li v-for="todo in todos" :key="todo.id" > {{ todo.text }} </li> </ul>
Never use v-if and v-for on the same element at the same time.
To filter items in a list
v-for="user in users" v-if="user.isActive"
v-for="user in users" v-if="shouldShowUsers"
<ul> <li v-for="user in users" v-if="user.isActive" :key="user.id"> {{ user.name }} </li> </ul>
this.users.map(function (user) { if (user.isActive) { return user.name } })
computed: { activeUsers: function() { return this.user.filter(function (user) { return user.isActive }) } }
<ul> <li v-for="user in activeUsers" :key="user.id"> {{user.name}} </li> </ul>
<ul> <li v-for="user in users" v-if="shouldShowUsers" :key="use.id"> {{user.name}} </li> </ul>
<ul> <li v-for = "user in users" v-if="user.isActive" :key="user.id"> {{user.name}} </li> </ul> <ul> <li v-for="user in users" v-if="shouldShowUsers" :key="user.id"> {{user.name}} </li> </ul>
<ul> <li v-for="user in activeUsers" :key="user.id" > {{ user.name }} </li> </ul> <ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id" > {{ user.name }} </li> </ul>
<ul> <li v-for="user in activeUsers" :key="user.id" > {{ user.name }} </li> </ul> <ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id" > {{ user.name }} </li> </ul>
<template> <button class="btn btn-close">X</button> </template> <style> .btn-close { background-color: red; } </style>
<template> <button class="button button-close">X</button> </template> <!-- Use `scoped` Characteristic --> <style scoped> .button { border: none; border-radius: 2px; } .button-close { background-color: red; } </style> <template> <button :class="[$style.button, $style.buttonClose]">X</button> </template> <!-- Use CSS Modules --> <style module> .button { border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style>
<template> <button :class="[$style.button, $style.buttonClose]">X</button> </template> <!-- Use CSS Modules --> <style module> .button { border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style>
<template> <button class="c-Button c-Button--close">X</button> </template> <!-- Use BEM Appointment --> <style> .c-Button { border: none; border-radius: 2px; } .c-Button--close { background-color: red; } </style>
The function of virtual Dom and Key attribute
<template> <div id="app"> <input v-model="message" > <input :value="message" @input="handleChange"> {{message}} {{message * message}} <div :id="message"></div> <todo-list> <todo-item @delete="handleDelete" v-for="(item, index) in list" :key="index" :title="item.title" :del=""> <template v-slot:pre-icon="{value}"> <span>{{value}}</span> </template> </todo-item> </todo-list>
vue is if a component update is triggered
<script> export default{ name: " ", props: { info: Object, name: String, list: Array }, data(){ return { a: ' ', b: ' ' }; }, updated() { console.log(' '); }, methods: { handleBChange() { this.b = "vue" +Date.now(); } } };
Reasonable application of computing properties and listeners
Reduce the calculation logic in the template Data cache Dependent on fixed data types (reactive data)
Calculation attribute: calculated
<p>{{ reversedMessage1 }}</p> <p>{{ reversedMessage2() }}</p> <p> {{ now }} </p> <button @click="() => $forceUpdate()">forceUpdate</button> <br/> <input v-model="message"/> export default { data() { return { message: 'hello' }; }, computed: { // getter of calculated property reversedMessage1: function() { return this.message .split("") .reverse() .join(""); }, now: function() { return Date.now(); } }, methods: { reversedMessage2: function() { return this.message .split("") .reverse() .join(""); }
Listener watch More flexible and versatile Any logic can be executed in watch, such as function throttling, ajax asynchronous data acquisition
<div> {{$data}} <br/> <button @click="() => (a += 1)"><button> </div> wxport default { data: function() { return { a: 1, b: {c:2,d:3}, e: { f: { g: 4 } }, h: [] }; }, watch: { a: function(val, oldVal) { this.b.c += 1; }, "b.c": function(val, oldVal) { this.b.d += 1; }, "b.d": function(val, oldVal) { this.e.f.g += 1; }
computed vs watch
All that can be done by computed can be done by watch, and vice versa Be able to use computed as much as possible
<div> {{ fullName }} <div> firstName: <input v-model="firstName"/></div> <div> lastName: <input v-model="lastName"/></div> </div> export default { data: function() { return { firstName: 'foo', lastName: 'bar' }; }, computed: { fullName: function() { return this.firstName + " " + this.lastName; } }, watch: { fullName: function(val, oldVal) { console.log("new",val,oldVal); } }
Application scenarios and functional components of vue life cycle
Life cycle:
Create phase, update phase, destroy phase
Creation phase: beforeCreate created beforeMount render mounted
Update phase beforeUpdate render updated
Destruction stage beforeDestory destoryed
Creation phase: beforeCreate created beforeMount render mounted
Initialize events and lifecycles beforeCreate Data observation, properties, listener configuration created Template compilation to render beforeMount render mounted Asynchronous request, operation dom, timer, etc
The stage of multiple updates
Update phase
beforeUpdate render updated
Rely on data changes or $forceUpdate to force refresh beforeUpdate Remove the added event listener, etc render updated Operate dom to add event listener and never change dependent data
Destruction phase: beforedestory destoryed
watch: { start() { this.startClock(); } },
Functional components: functional:true No state, no instance, no this context, no lifecycle
Functional components:
The essence of vue instruction
v-text v-html v-show v-if v-else v-else-if v-for v-on v-bind v-model v-slot v-pre v-cloak v-once
Custom instructions: bind inserted update componentUpdated unbind
Life cycle hook
Common advanced features provide/inject
The problem solved is the communication problem of components
Properties, communication Events, communications
How to get cross level component instances gracefully: Reject recursion
Citation information
<p ref="p">hello</p> <child-component ref="child"></child-component>
Auto notify setXXXref Get getxxxref actively
<button @click="getEH3Ref"></button export default { components: { ChildrenB, ChildrenC, ChildrenD }, provide() { return { setChildrenRef: (name, ref) => { this[name] = ref; }, getChildrenRef: name => { return this[name]; }, getRef: () => { return this; } }; },
<ChildrenH v-ant-ref="c => setChildrenRef("childrenH", c)"/> export default { components: { ChildrenG, ChildrenH, ChildrenI }, inject: { setChildRef: { default: () = {} } } };
The difference between template and jsx
How to use vuex in vue
import Vue from 'vue' import Vuex from 'vuex' import App from './App.vue' Vue.use(Vuex) Vue.config.productionTip = false const store = Vue.Store({ state: { count: 0, } }) new Vue({ store, render: h => h(App), }).$mount('#app')
increment({commit}) { setTimeout(()=>{ commit('increment') }, 3000) }
<template> <div id="app"> {{count}} </div> </template> <script> export default { name: 'app', computed: { count() { return this.$store.state.count } } } </script>
<button @click="$store.commit('increment', 2)">count++</button>
mutations: { increment(state, n) { state.count += n } }
Core concepts and underlying principles of vuex
Core concept State - > this. $store.state.xxx value Getter - > this. $store.getters.xxx value
Assignment - > this. $store.commit ("XXX") Action - > this. $store.dispatch ("XXX") assignment
module
Underlying principle: State: provide a responsive data Getter: using the calculated property of Vue to implement caching
mutation: changing the state method action: trigger mutaion method module:Vue.set dynamically add state to responsive data
vuex best practice
Using constants instead of the education event type
// mutation-type.js export const SOME_MUTATION="SOME_MUTATION" // store.js import Vuex from 'vues' import { SOME_MUTATION } from '' const store = new Vuex.Store({ state: { ... }, mutations { [SOME_MUTATION] (state) { } } })
Traditional development mode
www.xxx.com - index.html www.xxx.com/about -about.html
Use scenario of vue touter
Listen for url changes and execute corresponding logic before and after changes
Different URLs correspond to different components
Provide APIs to change URLs in many ways
Usage: Provide a routing configuration table. Different URLs correspond to the configuration of different components Initialize route instance new VueRouter()
Mount to vue instance Provide a route space to mount the components to which the Url matches
Which mode of routing to choose and the underlying principle
hash mode: ugly, unable to locate with anchor
What problems does Nuxt solve?
Nuxt core principle, SSR core principle
Ui component comparison Element UI,ANT design vue,iview
Improve development efficiency
Vetur,ESLint,Prettier,Vue DevTools
How does Vuex provide responsive data?
Expand the simplified version of Min Vuex, implement getters, and inject $store in the way of Vuex
Implementing getters caching with computed
How to get $store in beforeCreate
If the content of this number is not in place (for example, involving copyright or other issues), please contact us in time for rectification, and we will deal with it as soon as possible.
Please praise! Because your approval / encouragement is the biggest driving force of my writing!
Welcome to your attention. Dada The short book!
This is a blog with quality and attitude