VUE framework Part I: Basic knowledge and core principles

Basic concepts of VUE

cn.vuejs.org

Vue is a set of incremental frameworks for building user interfaces. Features: Easy to use, flexible, and efficient. + vue-router + vuex + vue-cli

Class libraries vs plug-ins vs components vs frameworks

  • Class libraries: jquery, Zepto, underscore…
  • Plugin: Dialog, banner, drag, TAB, iscroll…
  • Components: Bootstrap, swiper…
  • Frameworks: Backbone, Angular, vue, React, uni-app, React Native, flutter…

Declarative and imperative

  • Imperative programming: how do you command the “machine” to do something so that whatever you want it to do, such as the for loop
  • Declarative programming: tell the “machine” what you want and let the machine figure out how to do it, such as the array built-in method forEach

MVC  & MVVM

  • The traditional DOM mode of manipulation
  • MVC: Model View Controller
  • MVVM: Model view viewModel

<div id="app"> {{msg}} </div> <! -- IMPORT JS --> <script src="node_modules/vue/dist/vue.min.js"></script>
<script>
    new Vue({
    	el: '#app',
    	data: {
    		msg: 'hello world'}});setTimeout(() => {
    	vm.msg = Hello world;
    }, 1000);
</script>
Copy the code
< div id = "app" > : RMB $< input type = "text" v - model = 'price' > $< br > $: ${8} {price /} < / div > <! -- IMPORT JS --> <script src="node_modules/vue/dist/vue.min.js"></script> <script> let vm = new Vue({ el: '#app', data: { price: 0 } }); </script>Copy the code

Basic syntax for VUE

new Vue(options)

  • Return value VM (viewModel)
  • El: can’t mount to HTML or body =>querySelector
  • data
    • Data values must be declared for objects, otherwise new attributes are invalid (this can be done based on vm.$set).
    • Vm. arr[0]= XXX Changes an item in the array to a view that is not rendered, based on built-in methods such as: push…
    • Objects or arrays can replace values as a whole so that the data changes and the view changes
  • .

The person with the mustache [ˈ st ʌst ʃ

  • value
  • JS expression

Common directives (Directive)

  • v-model
  • V-html/V-text: Eliminates flicker in mustache syntax refresh
  • V-bind (abbreviated 🙂
  • v-once
  • V – if and v – show
  • v-for
    • For in loop & for of loop
      • Traverses the range of data types
      • Method traversal on the prototype (or traversal of the array’s new XXX: XXX property)
      • .
    • Symbol. Iteratoer: Array, Set, Map, String, Arguments, NodeList…
  • V-on event binding
    • v-on:xxx
    • Methods: Similar to data, methods are mounted to vm instances (this is the current instance).
    • @xxx
    • @xxx=”func” & @xxx=”func($event,…) “

Directive Indicates a custom directive

  • Vue.directive([Bindings, omit v-], function(EL, Bindings,vnode){}
    • El Current element
    • Bindings contain a lot of information
      • Name: indicates the command name, excluding the V – prefix
      • Value: Binding value of the directive
      • OldValue: The previous value of the directive binding, available only in the UPDATE and componentUpdated hooks
      • Expression: command expression in the form of a string
      • Arg: Optional parameter passed to the instruction. For example, in v-my-directive:foo, the parameter is “foo”.
      • Modifiers: Objects that contain modifiers. For example, in my-directive.foo.bar, the modifier object {foo: true, bar: true}
    • Vnode virtual DOM
      • CTX = vnode.context Gets the context of the current element
      • CTX [binding.expression]= XXX gets the expression variable in the context and assigns the specified value to it
  • Hook function
    • Bind: takes effect when the user binds a directive (only once)
    • Update: called when the VNode of the component is updated, but may occur before the VNode of its child is updated.
    • ComponentUpdated: Invoked when the VNode of the component where the directive resides and its child VNodes are all updated
    • Unbind: Called only once, when an instruction is unbound from an element
    • Inserted: Called when a bound element is inserted into a parent node (the parent node is guaranteed to exist, but not necessarily already inserted into the document)
  • Exercise: Create a checksum for a custom command control text box

Event modifier

  • .stop /.prevent /.once…
  • Key:.Enter or.13 /.up /.down /.left /.right…
  • Combinatorial modifier
  • .

Processing of form elements

  • A plain text box or text field
  • Radio buttons
  • Check box
  • A drop-down box
  • Case study: all and not all

Evaluate properties, filters, listeners

  • Methods common methods
  • Filters filter
    • Applies only to beard syntax and V-bind
    • Exercise: Capitalize the first letter of the word you enter
  • computed
    • getter & setter
    • Computed properties are cached based on their reactive dependencies, as opposed to normal methods
    • Depend on data variables in data
    • Exercise: Capitalize the first letter of the word you enter
    • Small exercise: all and not all
  • watch
    • Listeners are applied when asynchronous or expensive operations need to be performed when data changes
    • Small exercise: all and not all
    • Exercise: Data asynchronous binding processing
data(){ &emsp; &emsp;return{ &emsp; &emsp; &emsp; &emsp; checked:false.// Whether to select all&emsp; &emsp; &emsp; &emsp; checkModel:[] &emsp; &emsp; }},watch:{ &emsp; &emsp; checkModel(){ &emsp; &emsp; &emsp; &emsp;if(this.checkModel.length==this.list.length){ &emsp; &emsp; &emsp; &emsp; &emsp; &emsp;this.checked=true; &emsp; &emsp; &emsp; &emsp; }else{ &emsp; &emsp; &emsp; &emsp; &emsp; &emsp;this.checked=false; &emsp; &emsp; &emsp; &emsp; } &emsp; &emsp; }}...Copy the code

Class and style binding

  • Class handling (object syntax, array syntax)
  • Inline style handling
  • .

Lifecycle functions (hook functions)

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestory
  • destory
  • .

Common attribute methods

  • $set: Sets reactive data
  • $el: mounted element
  • $destroy: Vue instance destroyed; Call beforeDestroy destroyed as well
  • $mount: The method to mount the real DOM
  • $data: responsive object
  • $options: is an argument to the Vue constructor
  • $refs: Can be used to get the specified element object (uncontrolled component)
  • $on: subscriptions
  • $emit: release
  • $watch: monitoring
  • .

Example: TAB

Example: Shopping cart calculator

Case: Mall category screening


The implementation principle of two-way data binding

  • Object.defineProperty
  • Underlying principles of implementation
/ / the observer: the observer
function observer(obj) {
	if (obj && typeof obj === 'object') {
		for (let key in obj) {
			if(! obj.hasOwnProperty(key))break; defineReactive(obj, key, obj[key]); }}}function defineReactive(obj, key, value) {
	observer(value);
	Object.defineProperty(obj, key, {
		get() {
			return value;
		},
		set(newValue) {
			observer(newValue);
			if (value === newValue) return; value = newValue; }}); }function $set(data, key, value) {
	defineReactive(data, key, value);
}
Copy the code


  • Implement a listener Observer that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data.
  • Implement a parser Compile: parse Vue template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update.
  • Implement a subscriber Watcher: The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.
  • Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.

Components in VUE

The features of the components are:

  • Each component is a custom tag
  • reusable
  • Convenient maintenance
  • Convenient split
  • Scope isolation for each component (non-interference)
  • There is a full life cycle
  • Has its own responsive data and various methods (events)
  • .

1. Basic syntax for global components & components

Vue.com Ponent (componentName,options) Vue.com Ponent (componentName,options)

  • A little specification in the component name
    • Kebab-case: can only be called
    • PasalCase: can be called either in the same way or in the same way
  • Detail specifications for invoking components
    • Double closure mode is adopted
    • Single closure does not conform to W3C specification (only one can be recognized)
  • template
    • Each component can have only one root element
    • Template string mode
    • Template notation
    • Slot Slot processing
      • Basic operation
      • Multiple slot specification
  • Data must be a function that ensures that data from different components does not interfere with each other (initialized data in the returned object)
  • .
<my-component> <template V-slot: XXX or # XXX > Always be kind </template> </my-component> {templete: '<div> <slot name=' XXX '></slot>  </div>` }Copy the code

2. Local components

  • Let componenName={… }
  • Declare components based on the Components property: Which component you want to use needs to be declared first
  • Using the component

3. Parent transmission of component communication: props property transmission

  • When the parent component is called
<my-component aa='hhh' :bb='xxx'></my-component>
Copy the code
  • The child component declares the values of the properties to be received based on props
Vue.component('my-component', {props: ['aa'.'bb'],... })Copy the code
  • Properties declared in props, like data, are reactive data that is mounted to the VM instance and controls view rendering
  • Some details in props
    • Name case: pass kebab-case format, get camelCase camel name in props
    • Specifies the type of the property: props:{XXX :String,… }
    • Default values for the specified properties :{XXX :{type:String,default:’ XXX ‘,required:true}}
      • If type is an array, any of the specified types can be used
      • Default can be a function that returns the default value
      • Validator Custom validation rule functions: Must conform to the rules specified in the function and return true/false
    • The default values are strings. If you want the values to be numeric, Boolean, array, object, etc., you need to use V-bind
    • Style and class auto-merge issues

4. One-way data flow of VUE

All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around.

Vue’s parent and child component lifecycle hook function execution sequence can be categorized into the following four parts:

  • Loading the rendering process: Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted
  • Child component update process: Parent beforeUpdate -> child beforeUpdate -> Child updated -> Parent updated
  • Parent component update process: Parent beforeUpdate -> Parent updated
  • Destroy process: Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed

Every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. If a child component wants to modify it, it can only send a custom event through $emit. If the parent component receives the custom event, the parent component can modify it. There are two common situations when trying to change a prop:

  • This prop is used to pass an initial value; This child component next wants to use it as a local prop data. In this case, it is best to define a local data property and use the prop as its initial value
  • This prop is passed in as a raw value and needs to be converted. In this case, it is best to use the value of the prop to define a calculated property

5. Component communication child change parent: this.$emit

  • Subscribe to custom events: pass a method (parent) based on a property when a component is called
<my-component @func='xxx'></my-component>New Vue({methods:{XXX (value){//=>value}}});Copy the code
  • Notify custom event execution (child)
{
	methods:{
		xxx(){
			this.$emit('func'.10); }}}Copy the code
  • This method can also be used to realize information communication between sibling components (parent and child components, intergenerational components)
let eventBus=new Vue; //=> Create an event bus

/ / A component
eventBus.$on('xxxA'.this.func);

/ / B component
eventBus.$emit('xxxA');
Copy the code

6. Realize parent-child component information communication based on REF

  • Ref, if used on a normal DOM element, refers to the DOM element. When used on a child component, the reference points to the component instance, which allows you to quickly retrieve and manipulate data in the child component
  • Children is an instance of getting components and children, except that $children is an array collection that requires us to remember the order of the components

7. Implement communication between ancestors and descendants based on provide and Inject

  • Ancestor components register data needed by descendant components based on provide
{
	provide: {//=> objects or functions that return objects (attribute values that are data in data must be processed using function methods)
		name:'hhh'.year:10},... }Copy the code
  • Descendant components declare data to be used based on Inject and retrieve it for use
{
	inject: ['name'].methods:{
		func(){
			let name=this.name; }}}Copy the code

TRANSITION animation in VUE

1. When will animation be used

  • Conditional render V-if
  • Conditional display V-show
  • Dynamic components such as vue-router control component rendering
  • .

2. How to achieve animation

  • Modify the style of the element: style & class
  • Animation with JS (the first two weeks in some scenes require direct manipulation of DOM or more trouble)
  • Use transition & Transition-group built into VUE

3. Basic Use of Transition

  • V-enter: Defines the start state of the transition, which takes effect before the element is inserted and is removed in the next frame after the element is inserted
  • V-enter-active: Defines the state when the transition is in effect, applied throughout the transition, before the element is inserted, and removed after the transition/animation is complete
  • V-enter -to: Defines the end state of the transition. The element is inserted after the next frame, and removed after the transition/animation is complete
  • V-leave: Defines the start state of the exit transition. It takes effect immediately when the exit transition is triggered and the next frame is removed
  • V-leave-active: Defines the state in which the exit transition is in effect, applies throughout the exit transition phase, takes effect immediately when the exit transition is triggered, and removes after the transition/animation is complete
  • V-leave-to: Defines the end state of the exit transition, which takes effect in the next frame after the exit transition is triggered and removed after the transition/animation is complete
  • Animate style discrimination based on the name attribute in the Transiton tag
    • The demo – enter, etc
  • Custom transition class names (for example, used with animate. CSS)
    • <transition

      enter-active-class=”animated xxx”  leave-active-class=”animated xxx”

4. Animate hook functions in JAVASCRIPT

  • Velocity. Js function
<transition
  @before-enter="beforeEnter"
  @enter="enter"
  @after-enter="afterEnter"
  @before-leave="beforeLeave". ></transition>

methods:{
	 beforeEnter: function (el,done) {},... }Copy the code

Transition-group handles multi-group element animations

  • If v-for is used in transition-group, the key value must be unique
  • Small exercise: keyword fuzzy matching search

Comprehensive combat case

1. Implementation of round-cast graph

2. TASK OA (commonly known as TODO)