Vue 2.0 基础知识点
- 特点
- 实例
- 基本语法
- 生命周期
- 路由管理Vue-Router
- 状态管理Vuex
- Http请求库Axios
由MVC架构衍生,分为View(视图层)、ViewModel(数据视图层)、Model(数据层),MVVM 最标志性的特性就是 数据绑定,实现数据驱动视图,视图同步数据 。
2.数据也是单向的,称之为单向数据流
数据总是从父组件传递到子组件中,子组件无权(不建议)直接修改父组件中的数据 。
3.不兼容ie8及其以下浏览器
响应式原理式利用了es5的Object.defineProperty,而该API不支持IE8
实例
// Vue单页面实例<template>标签...</template><script>export default {data () {},methods: {},computed: {},watch: {}}</script><style>样式...</style>选项 Optionsdata函数,用于定义页面的数据
data() {return {count: 2copyCount: 1}}// 使用this.count // 2computed对象,计算属性,用于简化复杂逻辑处理
// 计算属性不接受参数,会缓存依赖数据,必须要有returncomputed:{doubleCount: function () {return this.count *= 2},}// 使用this.doubleCount // 4methods对象,用于定义页面的函数
methods: {cLog(msg) {console.log(msg)}}// 使用this.cLog('调用了函数') // 控制台输出:调用了函数watch对象,属性侦听,用来监听某数据的改变并做出对应操作
watch: {count(value, [oldValue]) {// value:改变后的值this.copyCount = value + 1}}// 当count发生改变时自动触发this.count = 2this.copyCount // 3components对象,注册组件到页面
import UploadImg from 'xxxx'components: { UploadImg }// template<upload-img>基本语法常用指令v-html渲染HTML
v-if
判断语法,控制显示/隐藏,通过是否渲染DOM来控制
v-show
控制显示/隐藏,与v-if类似,但v-show是通过display属性控制
v-model
双向数据绑定,一般用于表单,默认绑定value属性
v-bind
简写 :class
用于动态属性绑定
v-on
简写 @click
用于事件绑定
v-for
遍历语法,支持数组、对象及字符串
生命周期beforeCreated
创建Vue对象
created
data初始化,此时可以对实例做些预操作
beforeMounted
el和data初始化
mounted
挂载el和data,此时可以调用http请求
beforeUpdated
更新DOM前,此时可以进一步地更改状态,不会触发重渲染过程
updated
更新修改后的虚拟DOM到页面,此时应避免改动操作,以免造成无限循环更新
beforeDestory
页面销毁前,此时可以做一些重置操作,比如清除定时器 和 dom事件等
destoryed
页面销毁,此时Vue实例已被删除,所有操作均无效
路由管理Vue-Router官方的路由管理器 。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌 。
路由配置
// NPM下载npm install vue-router// router.jsimport Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)// 定义页面路由(路径、组件)export default new Router({{ path: '/foo', component: () => import('/pages/foo') }, // 路由组件懒加载{ path: '/bar', component: '/pages/bar'}})// main.jsimport router from './router.js'new Vue({el: '#app',router, // 挂载路由到Vue实例render: h => h(App)})// page.vue<!-- 要重点区分开两者的关系 -->this.$router // 访问路由器,内置push、replace的路由方法this.$route // 访问当前路由,内置path、query等路由属性// app.vue<!-- 路由匹配到的组件将渲染在这里 --><router-view></router-view>路由跳转申明式路由<router-link :to="..."><router-link :to="..." replace>编程式路由this.$router.push({ path: 'register', query: { plan: 'private' }})this.$router.replace(...)// 与push区别在不插入history记录this.$router.go( [Number] n )// 在 history 记录中向前或者后退多少步// 路由传参携带中文时建议先使用encodeURLComponent转码,以免显示乱码 。路由守卫导航守卫|Vue-Router官方文档全局守卫对配置的所有路由均生效,但优先级低与内部路由 。
全局前置守卫(常用)
// 用户未能验证身份时重定向到 /loginrouter.beforeEach((to, from, next) => {// to 即将要进入的路由对象,from 来源路由,next 钩子函数,是否放行if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })else next()})全局解析守卫(了解)router.beforeResolve((to, from, next) => {// ...})全局后置钩子(了解)router.afterEach((to, from) => {// 该路由守卫不接受 next 钩子函数// ...})路由独享守卫(了解)该守卫仅对配置的路由生效,这些守卫与全局前置守卫的方法参数是一样的 。const router = new VueRouter({routes: [{path: '/foo',component: Foo,beforeEnter: (to, from, next) => {// ...}}]})组件内部守卫(了解)可以在路由组件内直接定义以下路由导航守卫,仅对当前组件生效 。beforeRouteEnterbeforeRouteUpdate (2.2 新增)beforeRouteLeave组件内的守卫 | Vue-Router官方文档状态管理器Vuex配置
// store.jsimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)...export default new Vuex.Store({state,getters,mutations,actions,modules})// main.jsimport store from './store'Vue.prototype.$store = store五大核心属性state数据源,不要直接修改state状态// store.jsconst state = {name: 'zzz'}<!--page.vue-->// 1.直接调用this.$store.state.name // 'zzz'// 2.辅助函数映射computed: {...mapState(['name'])}this.name // 'zzz' mutations改变state状态的唯一途径const mutations = {updateName(state, newName) {state.name = newName}}<!--page.vue-->// 1.直接调用this.$store.commit(updateName, 'zzh') // state.name: 'zzh'// 2.辅助函数映射methods: {...mapMutations(['updateName'])}this.updateName('zzh') // state.name: 'zzh'actions存放异步操作,异步触发mutation改变stateconst actions = {asyncUpdateName(context) {// 异步操作,例如发起http请求去获取更新后的name,假设name=xxx...context.commit('updateName', res.name) // state.name: 'xxx'}}<!--page.vue-->// 1.直接调用this.$store.dispatch(asyncUpdateName)// 2.辅助函数映射methods: {...mapActions(['asyncUpdateName'])}this.asyncUpdateName()getters数据源处理,类似计算属性const getter = {formatName(state) {return state.name + '2021'}}<!--page.vue-->// 1.直接调用this.$store.getter.formatName() // 'xxx2021'// 2.辅助函数映射computed: {...mapGetters(['formatName'])}this.formatName() //// 'xxx2021'modules模块化,让每个模块单独管理一套自己的state、mutations、actions和getters 。// 模块内部this.$store.state.name// 内部访问无须使用命名空间// 模块外部this.$store.state.login.name// login是模块命名空间...其他属性类似modules|Vuex官方文档Axios基于 promise 封装的Http请求库,官方推荐
<!-- api.js -->import axios from 'axios'// 创建并配置实例axios.create({baseURL: 'http://www.baidu.com',// 请求基准地址timeout: 1000// 请求超时时间...})// 请求拦截器axios.interceptors.request.use(request => {request.headers['Content-Type'] = 'application/json'...})// 响应拦截器axios.interceptors.response.use(response => {...return response.data})// 配置请求export default {getId: () => axios.get('/getId'),getNameById: id => axios.post('/getNameById', id)}<!-- main.js -->import api from './api.js'Vue.prototype.$api = api<!-- page.vue -->this.$api.getId().then(res => {...}).catch()【Vue 2.0 基础】本文来自博客园,作者:吴知木,转载请注明原文链接:https://www.cnblogs.com/zh1q1/p/15293290.html- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
