Vue 2.0 基础详细

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue 2.0 基础详细脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

// 计算属性不接受参数,会缓存依赖数据,必须要有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>

4、基本语法

常用指令

v-htML:渲染HTML

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

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

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

v-bind

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

v-on

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

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 路由守卫

全局守卫

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

全局前置守卫(常用)

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

7、状态管理器Vuex

7.1 配置

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

8、五大核心属性

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

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 基础内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Vue 2.0 基础详细全部内容,希望文章能够帮你解决Vue 2.0 基础详细所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。