您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

Vue 2.0 基础详细

51自学网 2022-02-21 13:39:21
  javascript

1、特点

是一个MVVM框架

由MVC架构衍生,分为View(视图层)、ViewModel(数据视图层)、Model(数据层),MVVM 最标志性的特性就是 数据绑定,实现数据驱动视图,视图同步数据。

数据也是单向的,称之为单向数据流

数据总是从父组件传递到子组件中,子组件无权(不建议)直接修改父组件中的数据。

不兼容ie8及其以下浏览器

响应式原理式利用了es5的Object.defineProperty,而该API不支持IE8

2、实例

// Vue单页面实例<template>    标签...</template><script>    export default {      data () {},      methods: {},      computed: {},      watch: {}    }</script><style>    样式...</style>

3、选项 Options

data

函数,用于定义页面的数据

data() {    return {        count: 2        copyCount: 1    }}// 使用this.count // 2

computed

对象,计算属性,用于简化复杂逻辑处理

// 计算属性不接受参数,会缓存依赖数据,必须要有returncomputed:{    doubleCount: function () {      return this.count *= 2    },}// 使用this.doubleCount // 4

methods

对象,用于定义页面的函数

methods: {    cLog(msg) {        console.log(msg)    }}// 使用this.cLog('调用了函数') // 控制台输出:调用了函数

watch

对象,属性侦听,用来监听某数据的改变并做出对应操作

watch: {    count(value, [oldValue]) {        // value:改变后的值         this.copyCount = value + 1    }}// 当count发生改变时自动触发this.count = 2this.copyCount // 3

components

对象,注册组件到页面

import UploadImg from 'xxxx'components: { UploadImg }// template<upload-img>

4、基本语法

常用指令

v-html:渲染HTML

v-if:判断语法,控制显示/隐藏,通过是否渲染DOM来控制

v-show:控制显示/隐藏,与v-if类似,但v-show是通过display属性控制

v-model:双向数据绑定,一般用于表单,默认绑定value属性

v-bind

  • 简写 :class
  • 用于动态属性绑定

v-on

  • 简写 @click
  • 用于事件绑定

v-for:遍历语法,支持数组、对象及字符串

5、生命周期

beforeCreated:创建Vue对象

created:data初始化,此时可以对实例做些预操作

beforeMounted:el和data初始化

mounted:挂载el和data,此时可以调用http请求

beforeUpdated:更新DOM前,此时可以进一步地更改状态,不会触发重渲染过程

updated:更新修改后的虚拟DOM到页面,此时应避免改动操作,以免造成无限循环更新

beforeDestory:页面销毁前,此时可以做一些重置操作,比如清除定时器 和 dom事件等

destoryed:页面销毁,此时Vue实例已被删除,所有操作均无效

6、路由管理Vue-Router

官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。

6.1 路由配置

// 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>

6.2 路由跳转

申明式路由

<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转码,以免显示乱码。

6.3 路由守卫

全局守卫

对配置的所有路由均生效,但优先级低与内部路由。

全局前置守卫(常用)

// 用户未能验证身份时重定向到 /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官方文档

7、状态管理器Vuex

7.1 配置

// 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

8、五大核心属性

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改变state

const 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官方文档

9、Http请求库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 基础详细的文章就介绍到这了,更多相关Vue 2.0 基础内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


下载地址:
浅谈JS正则RegExp对象
打包非 JavaScript 静态资源详情
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。