Vue核心

Vue核心

1、Vue属性
1、$mount挂载

const app = new Vue({
        el: '#root',
        data: {
            text: 'text'
        }
    })
等同于:
const app = new Vue({
        data: {
            text: 'text'
        }
    })
    app.$mount('#root')

2、Vue属性:data、props、el、options、root、children、slots、scopedSlots、refs、isServer

console.log(app.$data)
console.log(app.$el)
console.log(app.$options)
console.log(app.$props)
console.log(app.$root)
console.log(app.$root === app) // true

data对应的就是就是实例的data里面的数据。 3、Vue方法:watch 、on 、emit、forceUpdate、set、nextTick、watch:监听某个属性

const app = new Vue({
        el: '#root',
        data: {
            text: 'text'
        },
       watch: {
            'text': (newVal, oldval) => {
                console.log(newVal);
            }
        }
 })
app.$watch('text', (newVal, oldval) => {
        console.log(newVal);
})

on: 监听某个方法emit: 执行某个方法

app.$on('test', (a, b) => {
        console.log(`test方法执行了${a} ${b}`);
})
app.$emit('test', 1, 3)

$forceUpdate: 强制渲染组件,不推荐使用,会影响性能

const app = new Vue({
        // el: '#root',
        data: {
            text: 'text',
            obj: {}
        },
    })
 setTimeout( () => {
        app.obj.a = `${app.text}  我是obj` // obj的属性a没定义,这里赋值无法成功
        app.$forceUpdate() // 渲染组件,obj的a属性能赋值上
    }, 1000)

$set: 给data里的对象添加属性

const app = new Vue({
        // el: '#root',
        data: {
            text: 'text',
            obj: {}
        },
    })
app.$set(app.obj, 'b', '我是属性b') 

$nextTick:异步
2、生命周期

const app = new Vue({
        el: '#root',
        // template: '<div>{{text}}</div>',
        data: {
            text: 0,
            obj: {}
        },
        beforeCreate() {
            console.log(this.$el, 'beforeCreate')
        },
        created() {
            console.log(this.$el, 'created')
        },
        beforeMount() {
            console.log(this.$el, 'beforeMount')
        },
        mounted() {
            console.log(this.$el, 'mounted')
        },
        beforeUpdate() {
            console.log(this.$el, 'beforeUpdate')
        },
        updated () {
            console.log(this.$el, 'updated')
        },
        activated() {
            console.log(this.$el, 'activated')
        },
        deactivated() {
            console.log(this.$el, 'deactivated')
        },
        beforeDestroy () {
            console.log(this.$el, 'beforeDestroy')
        },
        destroy () {
            console.log(this.$el, 'destroy')
        },
        render (h) {
            //  throw new Error('render stack')  // 此代码会执行renderError
            return h('div', {}, this.text)
        },
        renderError (h, err) {
            return h('div', {}, err.stack)
        },
        errorCaptured (h) {
            return h('div', {}, err.stack)
        },
        watch: {
            'text': (newVal, oldval) => {
                console.log(newVal);
            }
        }

    })
    setTimeout(() => {
        app.text += 1
    }, 3000)

1)beforeCreate、created、beforeMounted、mounted都是一次性的,只在组件渲染时执行。beforeUpdate、updated数据改变时都会执行。
2)beforeCreated、created时DOM还未挂载,所以this.$el是underfined。
3)beforeMounted时render函数还未执行,所以根节点还是root,mounted时render已经执行完,节点就是render里渲染的内容或者是template里渲染的内容。template和render的作用是一样,都是渲染html内容。(render函数在beforeMounte和mounted之间执行)
4)renderError函数,只有在开发环境使用,打包环境不会使用,用来显示render函数的错误。
5)errorCaptured函数,会向上冒泡,如果在main.js里写函数,那么vue所有子组件的错误都会抛出。而且它可以在正式环境使用。
6)服务端只用beforeCreate和created函数,无beforeMounte和mounted,因为服务端无DOM操作。
3、Vue数据绑定
watch方法:
immediate: 组件渲染时就能watch到数据。如果不加immediate: true,组件刷新渲染时不会执行watch的handler方法。
deep:深层watch数据。deep:true可以监测到对象深层属性的改变,不然只能在对象重新赋值时才能执行watch的handler方法。
4、Vue指令
5、自定义双向绑定
6、Vue高级属性——插槽slot、以及作用域插槽slot-scope
7、Vue高级属性——provide和inject( 用于上下级组件)
8、Vue继承组件
9、Vue的render function
10、Vue-router的配置

new Router({
    routes,
    mode: 'history', // 去掉路由的#,便于seo
    base: '/base/', // 所有路由加统一的前缀路由
    linkActiveClass: 'active-link',// 部分匹配的路由添加的class
    linkExactActiveClass: 'exact-active-link' // 完全匹配的路由添加的class,
    scrollBehavior(to, from , savedPosition) {
     // 跳转页面,滚动条的位置,默认记录滚动条位置
          if (savedPosition) {
              return savedPosition
          } else {
              return {x:0,y:0}
          }
    },
    fallback: true, // 默认true,不是所有的浏览器支持histroy,
    parseQuery(query) {}, // 定义路由参数字符串转成json的方法
    stringifyQuery (obj) {} //  定义路由参数对象转成string的方法
})

11、Vue-router路由参数的传递

const routes = [
    {
        path: '/',
        redirect: '/app' // 路由重定向
    },
     {
        path: '/app/:id', // 匹配路由/app/xxx,xxx就是id,获取方式this.$route.params.id
        // props: true, // props使用比较灵活,设置true,id通过props传递接收,不需要this.$route.params.id获取,直接this.id获取
       props:(route) => ({id: route.query.b }), // this.$route.query.id获取的是路由(/app/123?id=456)中id的参数
        component: Todo,
        name: 'app', //  可以用于路由跳转
        meta: { // 一些和路由无关的参数可以放在meta,
            title: 'sssss', // 自己定义的
            description: 'ssss' // 自己定义的
        },
        children: [
           {
                path: 'test',
                component: Test
            },
        ]
    },
    {
        path: '/login',
        component: Login
    },
]

transtion:

// 路由切换时的过渡动画
<template>
<transition name="fade">
    <router-view />
 </transition>
</template>
<style>
.fade-enter-active,.fade-leave-active{
    transition: opacity 0.5s;
}
.fade-enter,.fade-leave-to{
    opacity; 0;
}
</style>

12、Vue-router的导航守卫
1)一个页面有多个router-view,多用于切换不同菜单


<template>
    <transition>
        <router-view />
    </transition>
      <router-view  name="AAA"/>
</template>
// 在router.js中
const routes = [
    {
        path: '/app',
        components: {
              default: Todo,
              AAA: Login
        }
    },
]

2)全局钩子

router.beforeEach((to, from, next) => { // 可以用于登录校验
      if (未登录校验) {
          next('/login')
          // next({path: '/login'})
          // next({name: 'Login'})
      } else {
          next()
     }
})
router.beforeResolve((to, from, next) => {
  next()
})
router.afterEach((to, from) => {
 
})
router.afterEach((to, from) => {
 
})

3)局部钩子

// router.js
const routes = [
    {
        path: '/app',
        component: Todo,
        beforEnter (to, from, next) { //  执行顺序:beforeEach之后,beforeResolve之前
            next()
        }
    },
]
// 组件内
<template>
</template>
<script>
export default {
    beforeRouteEnter (to,from,next) {
      console.log(this) // undefined
        next (vm => {
           console.log(vm) // vm 就是this
        })
    },  
    beforeRouteUpdate (to,from,next) { // 路由是/app/:id时触发,获取数据,使用这个方法可以减少watch开销
        next ()
    },
    beforeRouteLeave (to,from,next) { // 控制页面离开行为,可以用于是否提交用户的修改行为
        next ()
    },
}
</script>

4)异步组件

// 安装: 
npm i babel-plugin-syntax-dynamic-import  -D
// babelrc文件
plugin: [
    "syntax-dynamic-import"
]
const routes = [
    {
        path: '/app',
        component: () => import('../views/Todo.vue'),
    },
]

Vuex

1、Vuex之集成
state、mutations、getters、actions、
辅助函数mapState、mapMutations、mapGetters、mapActions、
mutations处理同步数据,actions处理异步数据


new Vuex.Store({
      strict: true, // 严格限制在组件内对state进行直接修改,必须通过mutations,不要在正式环境使用,在开发环境使用来规范代码
   // strict:process.env.NODE_ENV === 'development',
      state,
      mutations,
      action,
      getters
})
//使用
//state、getters写在computed里
this.$store.state.count---------mapState('count')
this.$store.getters.getCount ----- mapGetters('getCount')
//mutations、actions写在methods里
this.$store.commit(['updateCount'])
this.$store.dispatch(['updateCountAsync'])

2、Vuex之模块

new Vuex.Store({
      state,
      mutations,
      action,
      getters,
      modules: {
          a: {
              namespaced: true, // 不同模块可以写相同名字的mutations和actions
               state: {
                      text: '我是a'
              },
              mutations:{
                    updateText (state, text) {
                          state.text = text
                    }
              },
              getters: {
                  textPlus (state, getters, rootState) { // rootState全局的state
                        return state.text + rootState.b.text
                  }
              }
          },
          b: {
               state: {
                      text: '我是b'
              }
          }
      }
})
// 使用方式
let textA = this.$store.state.a.text 
// mapState({ textA: (state) => state.a.text })

热更新

export default () => {
    const store = new Vuex.Store({
      state,
      mutations,
      action,
      getters
  })
///热更新
   if (module.hot){
      module.hot.accept(
        [
            './state/state',  //路径
            './mutations/mutations',
            './getters/getters',
            './actions/actions',
        ], () => {
              const newState = require('./state/state').default
              const newMutations = require('./mutations/mutations').default
              const newGetter = require('./getters/getters').default
              const newActions = require('./actions/actions').default
              store.hotUpdate({
                    state: newState,
                    mutations: newMutations,
                    getters: newGetters,
                    actions: newActions
              })
        } )
    }
    return store
}

3、Vuex之API

// registerModule注册模块
store.registerModule('c', {
      state: {
          text: '我是c'
      }
})
//watch
store.watch((state) => state.count + 1, (newCount) => {
      console.log('new count watched', newCount)
})

store.subscribe((mutation, state) => {
      console.log(mutation.type) // 调了哪个mutations
      console.log(mutation.payload) // 调mutations传递的参数
})
store.subscribeAction((action, state) => {
      console.log(action.type) // 调了哪个action
      console.log(action.payload) // 调action传递的参数
})
ew Vuex.Store({
      state,
      mutations,
      action,
      getters,
      pulgin: [
            (store) => {
                  console.log('aaa')
            }
      ]
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值