VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > JavaScript教程 >
  • Vue 2.0 基础

Vue 2.0 基础

知识点

  1. 特点
  2. 实例
  3. 基本语法
  4. 生命周期
  5. 路由管理Vue-Router
  6. 状态管理Vuex
  7. Http请求库Axios

特点

1.是一个MVVM框架

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

选项 Options

data

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

data() {
    return {
        count: 2
        copyCount: 1
    }
}

// 使用
this.count // 2

computed

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

// 计算属性不接受参数,会缓存依赖数据,必须要有return
computed:{
    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 = 2
this.copyCount // 3

components

对象,注册组件到页面

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.js
import 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.js
import 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官方文档

全局守卫

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

全局前置守卫(常用)

// 用户未能验证身份时重定向到 /login
router.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) => {
        // ...
      }
    }
  ]
})
组件内部守卫(了解)

可以在路由组件内直接定义以下路由导航守卫,仅对当前组件生效。

beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave

组件内的守卫 | Vue-Router官方文档


状态管理器Vuex

配置

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
...

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules
})
// main.js
import store from './store'

Vue.prototype.$store = store

五大核心属性

state

数据源,不要直接修改state状态

// store.js
const 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官方文档


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()

本文来自博客园,作者:吴知木,转载请注明原文链接:https://www.cnblogs.com/zh1q1/p/15293290.html

 
刷新评论刷新页面返回顶部


相关教程