1. Features
It is an MVVM framework
Derived from the MVC architecture, it is divided into View (view layer), ViewModel (data view layer), and Model (data layer). The most iconic feature of MVVM is data binding, which realizes data-driven views and synchronizes data.
Data is also one-way, called one-way data flow
Data is always passed from the parent component to the child component, and the child component does not have the right (not recommended) to directly modify the data in the parent component.
Incompatible with ie8 and below browsers
Responsive principle utilizes es5, and this API does not support IE8
2. Example
// Vue single page instance<template> Label... </template> <script> export default { data () {}, methods: {}, computed: {}, watch: {} } </script> <style> style... </style>
3. Options
data
Functions that define the data of the page
data() { return { count: 2 copyCount: 1 } } // use // 2
computed
Objects, computed properties, used to simplify complex logic processing
// The calculation attribute does not accept parameters, and will cache dependent data. You must have a returncomputed:{ doubleCount: function () { return *= 2 }, } // use // 4
methods
Object, function used to define pages
methods: { cLog(msg) { (msg) } } // use('The function was called') // Console output: The function was called
watch
Object, attribute listening, used to listen for changes in a certain data and make corresponding operations
watch: { count(value, [oldValue]) { // value: the changed value = value + 1 } } // automatically triggered when count changes = 2 // 3
components
Object, register component to page
import UploadImg from 'xxxx' components: { UploadImg } // template <upload-img>
4. Basic syntax
Common instructions
v-html
: Render HTML
v-if
: judge the syntax, control display/hide, control by whether to render the DOM
v-show
: Control display/hide, similar to v-if, but v-show is controlled through the display attribute
v-model
: Bidirectional data binding, generally used for forms, default binding value attribute
v-bind
:
- Abbreviation: class
- For dynamic property binding
v-on
:
- Abbreviation @click
- Used for event binding
v-for
: traversal syntax, supporting arrays, objects and strings
5. Life cycle
beforeCreated
: Create a Vue object
created
: data initialization, you can do some pre-operations on the instance at this time
beforeMounted
: el and data initialization
mounted
: Mount el and data, you can call http request at this time
beforeUpdated
: Before updating the DOM, you can further change the status at this time, and the re-rendering process will not be triggered.
updated
: Update the modified virtual DOM to the page. At this time, change operations should be avoided to avoid infinite loop updates.
beforeDestory
: Before the page is destroyed, you can do some reset operations, such as clearing timers and dom events.
destoryed
: The page is destroyed, the Vue instance has been deleted at this time, and all operations are invalid
6. Router management Vue-Router
Official router manager. It is deeply integrated with the core, making it easy to build single-page applications.
6.1 Routing Configuration
// NPM downloadnpm install vue-router // import Vue from 'vue' import VueRouter from 'vue-router' (VueRouter) // Define page routing (path, component)export default new Router({ { path: '/foo', component: () => import('/pages/foo') }, // Lazy loading of routing components { path: '/bar', component: '/pages/bar'} }) // import router from './' new Vue({ el: '#app', router, // Mounting route to Vue instance render: h => h(App) }) // <!-- It is necessary to focus on distinguishing the relationship between the two --> this.$router // Access the router, built-in routing method for push and replacethis.$route // Access the current route, built-in routing properties such as path and query// <!-- The component that the route matches will be rendered here --> <router-view></router-view>
6.2 Routing jump
Declaration-style routing
<router-link :to="..."> <router-link :to="..." replace>
Programming routing
this.$({ path: 'register', query: { plan: 'private' }}) this.$(...) // The difference from push is that history records are not insertedthis.$( [Number] n ) // How many steps forward or backward in history record // When routing parameters are transported in Chinese, it is recommended to use encodeURLComponent to transcode first to avoid garbled code.
6.3 Router Guard
Global Guard
All routes configured are effective, but have low priority with internal routes.
Global front guard (commonly used)
// Redirect to /login when the user fails to verify the identity((to, from, next) => { // to the route object to be entered, from source route, next hook function, whether to release it if ( !== 'Login' && !isAuthenticated) next({ name: 'Login' }) else next() })
Global Analysis Guard (understand)
((to, from, next) => { // ... })
Global back hook (understand)
((to, from) => { // The route guard does not accept the next hook function // ... })
Route exclusive guard (understand)
This guard only takes effect on configured routes, and these guards have the same method parameters as the global front guard.
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
Internal guards of components (understand)
The following route navigation guards can be defined directly within the routing component, which only take effect on the current component.
beforeRouteEnter beforeRouteUpdate (2.2 New) beforeRouteLeave
Guards within components | Vue-Router official documentation
7. State Manager Vuex
7.1 Configuration
// import Vue from 'vue' import Vuex from 'vuex' (Vuex) ... export default new ({ state, getters, mutations, actions, modules }) // import store from './store' .$store = store
8. Five core attributes
state
Data source, do not modify the state state directly
// const state = { name: 'zzz' } <!----> // 1. Direct callthis.$ // 'zzz' // 2. Helper function mappingcomputed: { ...mapState(['name']) } // 'zzz'
mutations
The only way to change the state
const mutations = { updateName(state, newName) { = newName } } <!----> // 1. Direct callthis.$(updateName, 'zzh') // : 'zzh' // 2. Helper function mappingmethods: { ...mapMutations(['updateName']) } ('zzh') // : 'zzh'
actions
Store asynchronous operations, trigger mutation to change state asynchronously
const actions = { asyncUpdateName(context) { // Asynchronous operation, such as initiating an http request to obtain the updated name, assuming name=xxx ... ('updateName', ) // : 'xxx' } } <!----> // 1. Direct callthis.$(asyncUpdateName) // 2. Helper function mappingmethods: { ...mapActions(['asyncUpdateName']) } ()
getters
Data source processing, similar to calculation properties
const getter = { formatName(state) { return + '2021' } } <!----> // 1. Direct callthis.$() // 'xxx2021' // 2. Helper function mappingcomputed: { ...mapGetters(['formatName']) } () // // 'xxx2021'
modules
Modularity allows each module to manage its own set of state, mutations, actions and getters.
// Inside the modulethis.$ // No namespace is required for internal access// External modulethis.$ // login is the module namespace... Other attributes are similar
modules|Vuex official documentation
9. Http request library Axios
Http request library encapsulated based on promise, official recommendation
<!-- --> import axios from 'axios' // Create and configure instance({ baseURL: '', // Request a reference address timeout: 1000 // Request timeout ... }) // Request an interceptor(request => { ['Content-Type'] = 'application/json' ... }) // Response Interceptor(response => { ... return }) // Configuration requestexport default { getId: () => ('/getId'), getNameById: id => ('/getNameById', id) } <!-- --> import api from './' .$api = api <!-- --> this.$().then(res => { ... }).catch()
This is the end of this article about the basic detailed Vue 2.0. For more basic content related to Vue 2.0, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!