Vue start

Vue. Js is what

A set of progressive frameworks for building user interfaces (advocate less, don’t go beyond the call of duty, introduce functionality as needed during development, not all at once, somewhat similar to iterative development). Unlike other frameworks, VUE is designed to be applied layer by layer from the bottom up. Vue’s core library is only concerned with the view layer, which is easy to use and easy to integrate with third-party libraries or existing projects. When combined with modern toolchains and various supporting libraries, VUE is also perfectly capable of providing drivers for complex single-page applications.

Declarative rendering

The data and DOM are already correlated, and everything is responsive

Conditions and cycles

You can bind data not only to DOM text or attributes, but also to DOM structures

Processing user input

V-on event binding

Componentized application building

Component systems are another important concept for Vue because it is an abstraction that allows us to build large applications from small, independent, and often reusable components. If you think about it, almost any type of application interface can be abstracted into a tree of components

  • Relationship with custom elements

    The Web Components specification is complete and approved, but not implemented natively by all browsers. Web Components are currently supported natively in Safari 10.1+, Chrome 54+, and Firefox 63+. In contrast, the Vue component does not require any polyfills and behaves consistently across all supported browsers (IE9 and later). Vue components can also be wrapped in native custom elements if necessary. Vue components provide some important capabilities that pure custom elements do not, most notably cross-component data flow, custom event communication, and build tool integration.

Vue:

Vue instance

Vue life cycle

  • beforeCreate

    After instance initialization, before observing data and event configuration

  • created

    Called immediately after instance creation, data observation and event configuration complete, mount phase begins, el property is not visible

  • beforeMount

    Before mounting, the related rendering function is executed for the first time

  • mounted

    El was successfully mounted to vm.$el

  • beforeUpdate

    Called before data update

  • updated

    The dom component is updated. The DOM component is updated

  • beforeDestroy

    Before instance destruction

  • destroyed

Vue template syntax

  • v-once

    Execute only once

  • v-html

    Compile the content into HTML code

  • v-text

    Template like string, does not support HTML code

  • v-once

    Execute only once

  • The interpolation

    Execute only once

    • The text

      The most common form of data binding is text interpolation using “Mustache” syntax (double curly braces) or the V-once instruction

      • {{}}
      • v-once
    • Raw HTML

      Be careful when using V-HTML. Do not use dynamic V-HTML rendering of user information, easy to receive SSR attacks

    • Attribute

      This can be done using v-bind, which dynamically binds one or more properties, or a component prop, to an expression using a method or property

    • Using JavaScript expressions

      Supports ternary judgment for JS verification

  • instruction

    • parameter

      Some directives can accept a “parameter” followed by a colon to indicate the name of the event or property that will follow the binding

    • The dynamic parameters

      You can use a JavaScript expression enclosed in square brackets as an argument to a directive where the attributeName is evaluated dynamically as a JavaScript expression, and the resulting value is used as the final argument. For example, if your Vue instance has a data attributeName with a value of “href”, this binding will be equivalent to v-bind:href.

      • Constraints on dynamic parameter values

        Dynamic arguments are expected to evaluate to a string, null in exceptional cases. This special null value can be explicitly used to remove the binding. Any other value that is not a string will trigger a warning.

      • Constraints on dynamic parameter expressions

        Some characters, such as Spaces and quotes, are invalid in HTML attribute names.

    • The modifier

      The modifier is a special suffix indicated by a semicontal period. Used to indicate that an instruction should be bound in a particular way. For example, the.prevent modifier tells the V-ON directive to call event.preventDefault() for triggered events.

  • abbreviations

    • v-bind
    • v-on

Evaluate properties, listeners

  • computed

    You don’t have to give a value for initialization, you have caching

    • Calculate the get and set of attributes

      Get Gets the data set Settings

  • watch

    You need initial values, and if you can do both, use computed

  • methods

Class is bound to Style

  • class

    • Object syntax
    • Array syntax
  • style

    • Object syntax
    • Array syntax

Conditions apply colours to a drawing

  • v-if

    V-if is “true” conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch. V-if is also lazy: if the condition is false during initial rendering, nothing is done — the conditional block is not rendered until the condition is true for the first time. V-show, by contrast, is much simpler — elements are always rendered regardless of initial conditions and simply switch based on CSS.

    • It is not recommended to use both V-if and V-for. Consult the style guide for more information.
  • v-show

    V-show, by contrast, is much simpler — elements are always rendered regardless of initial conditions and simply switch based on CSS. In general, V-if has a higher switching overhead, while V-show has a higher initial rendering overhead. Therefore, v-show is good if you need to switch very frequently; It is better to use V-if if conditions rarely change at run time.

  • The key value in the input

    You can clear out the content

The list of rendering

V – for = ‘item of itemArr’

  • Use V-for to map an array to a set of elements

    We can use the V-for directive to render a list based on an array. The V-for directive requires a special syntax of the form item in Items, where items are the source data array and item is the alias of the array element being iterated over.

  • Use objects in V-for

    Taking three arguments (value, name, index) when traversing an Object, the result of object.keys () is traversed, but there is no guarantee that its results will be consistent across JavaScript engines.

  • Maintaining state

    Do not use non-primitive values such as objects or arrays as v-for keys. Use a string or numeric value.

  • Array update detection

    • Variation method

      push pop sheift unshift splice sort reverse

    • Replace the array

      Filter (), concat(), and slice(). They do not alter the original array, but always return a new one. When using the non-mutating method, you can replace the old array with the new one

    • Matters needing attention

      • Due to JavaScript limitations, Vue cannot detect changes to the following arrays:

        • Vue.set(vm.items, indexOfItem, newValue)
        • vm.items.splice(indexOfItem, 1, newValue)
  • Note on object change detection

Vue. Set (Object, propertyName, Value) - Multiple objects modify vm.userProfile = object. assign({}, vm.userProfile, {age: 27, favoriteColor:'Vue Green'
	  })
Copy the code
  • Displays filtered/sorted results

    • Sometimes we want to display a filtered or sorted version of an array without actually changing or resetting the original data. In this case, you can create a calculated property to return a filtered or sorted array.

      • Using computed properties
      • Method, passing an array as an argument
  • v-for

    • To loop over a piece of content that contains multiple elements.
  • V-for is used with v-if

    • Note that we do not recommend using V-if and V-for on the same element

      V-for has a higher priority than V-if

  • Keys are now required when using V-for on components.

The event processing

  • To monitor events v – on | | @

  • Event modifier

    • stop

      • Prevent click events from propagating further (prevent bubbling)
    • prevent

      • Eliminate browser mode events
    • .capture

      • Use event capture mode when adding event listeners
    • self

      • That is, events are not triggered from internal elements
    • once

    • passive

In-depth understanding of VUE components

Details in the use of the build

  • is

    Tabel >tbody>tr> TD,ul>li

  • Data uses functions (remove root instances)

    The root component uses an object because it’s only called once and the component is concerned with reuse, so if you use an object, it’s a reference type, one change, everything else responds, so you use a function to return an object, so you don’t want to pollute it. Internal data is kept separate data storage

  • ref

    • dom

      We do not recommend manipulating the DOM in vUE, but we can use ref to get a reference to the DOM when we need to manipulate animation.

    • To form a

      When a REF is used in a build. What we get is a reference to the component

Parent-child data transfer

  • parent-child

    Pass the value through the props property. Values can be objects, arrays, strings, etc., single data stream, child component cannot modify the value passed in by the parent component. Because other places can reference the build, too. One change, other places can also affect.

  • Father son –

Component parameter verification and uncomponent PORPS features

  • Porps accept type

    It can accept multiple types, such as objects, arrays, and strings. The value can be extended. Type: Data type require: Whether to pass defult: default value validator: custom verification function

  • Porps features

    Parent to Child: The child component is accepted and does not appear in the DOM tag.

  • The porps features

    An error occurs if the parent sends a message but the child does not receive it. It is not practical and will display directly on the DOM node (HTML)

Bind native events to the build

Add @click.native=’fn’ to event binding

Not father and son make a decree

  • eventBus

    Using the event bus mechanism, inter-component messaging is implemented by mounting properties on the vUE prototype and pointing to the instance, so that methods on the VUE instance are available on the bus at any time

Use slots in VUE

  • Slot usage in vUE

    Insert labels into components and use slots to solve sub-components

    <ps content='youzi'>
        <header slot="header"> I'm header</header> <! <p> I am a donkey </p> --> <footer slot="footer"> I am footer</footer> </ps> </div> <script>'ps', {
        template: `<div>
            <slot name='header'></slot> <p> hahaha </p> <slot name='footer'></slot>
          </div>`
      })
    Copy the code
  • A named slot

    Add the name using the solt attribute, and use the name name in the child component

  • The default slot

    The parent component does not write content, the child component uses “solt” and “/solt” to display content

Scope slot

  • The default slot

    The parent component does not write content, the child component uses “solt” and “/solt” to display content

Animation effects in VUE

Single element/component transitions

When an element is inserted or removed from the Transition component, Vue automatically sniffs out whether CSS transitions or animations have been applied to the target element, and if so, adds/removes CSS class names when appropriate. The transition component provides JavaScript hook functions that will be called at the appropriate time. If the JavaScript hook is not found and CSS transitions/animations are not detected, the DOM operation (insert/delete) executes immediately on the next frame. (Note: this refers to the frame-by-frame animation mechanism of the browser, unlike Vue’s nextTick concept.)

The class name of the transition

  • v-enter

    Defines the beginning state of the transition, which takes effect before the element is inserted. The element is removed the next frame after it is inserted.

  • v-enter-active

    This class can be used to define the time, delay and curve functions of the transition into effect.

  • v-enter-to

    Define the end state of the transition. The next frame takes effect after the element is inserted (the V-enter is removed at the same time) and removed after the transition/animation is complete.

  • v-leave

    Define the beginning state of the exit transition

  • v-leave-active

    Defines the state when the exit transition takes effect. Applies throughout the exit transition phase, takes effect immediately when the exit transition is triggered, and removes after the transition/animation is complete. This class can be used to define exit transition process time, delay and curve functions.

  • v-leave-to

    Define the end state of the exit transition. The next frame takes effect after the exit transition is triggered (and the V-leave is deleted at the same time), and is removed after the transition/animation is complete.

CSS transition

CSS animations

CSS animations are used in the same way as CSS, except that the v-Enter class name is not deleted immediately after the DOM is inserted, but when the AnimationEnd event is triggered.

Custom transition class name

You can use the name attribute to bind the class name or enter-active-class leave-active-class

Use the animate. CSS library in Vue

The introduction of the animate. Js, bind enter-active-class= ‘animated class name ‘leave-active-class=’animated class name’

Use both transitions and animations

Use the animate. The CSS binds the class name to the Transition tag and then adds the animation name to the transition. You need to use the Type attribute and set the animation or Transition to explicitly declare the type that you want the Vue to listen to.

Transition from initial rendering

Use appear and use appearance-active-class

The duration of the apparent transition

You can either use a value directly or accept an object, where you can set the transitions between Enter and leave, respectively

Transitions of multiple elements

Ternary judgment or switch can be used

Transition mode

The default behavior of enter and leave occurs simultaneously. Both buttons have been redrawn, one leaving the transition and the other entering the transition. You can set it by mode, which has two properties, one out-of-in and one in-out

Transitions of multiple components

Transitioning from multiple components is much easier – we don’t need to use key attributes. Instead, we only need to use dynamic components: when building dynamic renderings, because entering and leaving happen at the same time. , transition when one leaves and transition when the other enters, so need to add attribute to operate mode=’out in’

List the transition

  • Instead, it will be rendered as a real element: the default is one. You can also use tag attributes for other elements
  • Transition mode is not available because we no longer switch unique elements between each other.
  • The inner element always needs to provide a unique value for the key attribute.
  • CSS transitioning classes will be applied to internal elements, not the group/container itself.

Home page project

The problem

  • Swiper displays the fourth image by default, not the first

    Swiper is created from an empty array that is passed in before ajax requests data from swiper. By default, swiper will display the length of the array.

  • UI component penetration

    Use /deep/ to do this

  • The page is not loaded, and there is data on the page

    The problem is that the picture is not loaded and the height is 0, the page will shake. Width :100% height:0 overflow:hidden padding-bottom: % Use vh,vw width:100% height:(height/width)vw

  • Swiper image 2 page rotation

    Using the calculation property, replace the original one-dimensional array with a 2-dimensional array, Const pages = [] this.list.forEach((item, index) => {const page = math.floor (index / 8) if (! pages[page]) { pages[page] = [] } pages[page].push(item) }) return pages

  • axios

    Use Vue. Use (axios)

    • use

      Get (‘ DSDSD ‘) import axios from ‘axios’ vue.prototype. axios = axios

  • mock

    The difference between vue-cli2 and vue-cli3 when using mock data is that vue-cli3 removes the static folder and now puts all the static resources in public

To optimize the

  • Extract global styles
  • Extract the public CSS

Preparing for project initialization

Multi-page application

Presentation: the page jumps to update the page. Page reloads benefits: The first screen of the page loads quickly, and only one HTTP request is made because the server returns an HTML file. Seo effect is good, because the search engine can identify THE HTML code, the page ranking, the weight of the page content has a good optimization disadvantage: slow page switching

Single page

However, the page will not be requested many times. Js senses changes through URL and dynamically mount the page required by JS to the front end for routing. Does not request each time, nor does the page reload. Benefit: page switch time fast jump, js render faults: first screen load time is slow, seo is poor, because the requests for an HTML page is not only to send js requests at the same time, this will all return to the page content display Due to the SSR is a rendering of a service, but the page is the client to render the request data dynamically add on. So SEO can’t see the data

Mobile terminal adaptation scheme

  • lib-flexible+postcss-px2rem

    Libn-flexible principle: By obtaining the layout viewport of the page, and then divide it into 10 points, such as 375,375/10 =37.5. 1rem=37.5px. The design elements you get are 75, 75/37.5=2rem. Document. The documentElement. GetBoundingClientRect (). The width / 10 for rem is according to the root element (HTML) nodes of the font size to calculate, We can use the px2REM plugin for PostCSS to help us with this process. Automatically adjusts HTML fontSize when window resize and pageShow events are triggered.

    • yarn add lib-flexible postcss-px2rem

    • Always introduce import ‘lib-flexible’ in main.js

    • Remove meta and comment from the Settings viewport in project /public/index.html

    • The root path creates vue.config.js with postcss-px2rem set

      Exports = {CSS: {// enable CSS modules modules: false, // whether to use CSS module extract: True, // Enable CSS source maps? SourceMap: false, // CSS default loaderOptions: {CSS: {}, postcss: {plugins: [//remUnit] What numbers do we remUnit for the configuration item? We usually get it based on the blueprints for the simple reason that it saves for development. // If the designs get remunerit to 750, we usually save it for 75, so we can get 1:1 out of the design when we write things. Require (‘ postCSs-px2rem ‘)({remUnit: 75})]}}}}

  • Vh, VW scheme

    • yarn add -D postcss-px-to-viewport

    • Set CSS configuration items in Config

      module.exports = { css: { loaderOptions: { postcss: { plugins: [ require(“postcss-px-to-viewport”)({ viewportWidth: ViewportHeight: 1334, // The height of the window is specified according to the width of the 750 device, generally specified 1334. ViewportUnit: ‘vw’, // Specify the window unit to convert to. Use vw. FontViewportUnit: “Vw “, selectorBlackList: [], // Specify a class that is not converted to a window unit. It can be customized and added indefinitely. It is recommended to define one or two common class names. 1, // less than or equal to 1px does not convert to window units, you can also set it to whatever value you want.mediaQuery: false, // Allows conversion of px.replace: true, exclude: /(/|\)(node_modules)(/|\)/, }) ] } } } }

Reset CSS

Use the reset.css plug-in library

Mobile 1px border issue

Mobile terminal click event delay processing

List page development

betterScroll.js

Page scrolling

City initials scroll

This.$refs[‘A’][0].offsetTop; Gets the distance from the top of the finger slide. E.ouches [0].clienty – 72(navigation height) Current index (index) index= math.floor ((clientY – this.starty) / 17); 17 is the height of each letter

Performance optimization

  • Use update to store fixed data, such as the distance of the A element from the top.

  • Use closure function (sliding to change position + search)

  • keep-alive

    Store loaded data in memory to avoid multiple rendering costs. After use, vUE has two lifecycle hook functions activated deactivated that can be used when the page exits

  • When the page uses VUex to change data, refresh data cannot be saved?

    Using localstorge

vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{city:'Beijing'},
	actions:{
		changeCity:({commit},val)=>{
				commit('changeCity',val)
		}
	},
    mutations:{
		changeCity(state,val){
			state.city=val		
		}
	}

})
Copy the code
  • state

    Equivalent to a separate storage space, the common data storage place is used in two ways in the build. this.$store.state.xxx this.city

    ``` import { mapState } from 'vuex' computed: { ... mapState(['city']) }, ```Copy the code
  • actions

    Asynchronous operations change data, batch operations put here, equivalent to an event trigger using the method: the component fires through this.router.push(‘/’) }, … mapActions([‘changeCity’])}

  • mutations

    Actions uses commit to call mutations, which changes the data.

  • Getter

    Similar to the calculation properties in VUE, such as using state data at the same time, can be split with getters to avoid data redundancy

  • Module

    For large projects, in the case of large amount of page data, the data required by each component can be taken out separately as a module to use. And then finally put it together

Nuxt framework vuEX writing modified

Export const modules = {geo, home, user} from new vuex.store (modules:{})

Detail page development

Public gallery construction using swiper dynamic data page sliding problems

  • why

    At first our build was in a hidden state, but when it was displayed again, swiper had a problem calculating the width, causing the rotation graph to not work properly

  • To solve

    Swipe updates when the window changes and listens for dynamic self-update when the parent changes. Add two properties to swiperOptions: observeParents:true, Observer :true

Implement the fade – in content of Heade

Set 2 part, through the v – show to judge which one show, fade fade in the main document. The documentElement. The scrollTop && document. The body. The scrollTop to calculate the position of the scroll effect

Unbinding of global events

If binding to one of the component elements doesn’t matter but binding to the global window, no matter where the component is, there are two new lifecycle functions that will be added when we use the keep-Aliveb wrapper to build, Activated activated (cache use) when deactivated (go call) to form a hidden window. The removeEventListener (‘ ‘)

Implement a list of detail pages using recursive building blocks