1分钟掌握Vue基础

140 阅读1分钟

1、父子组件传值方式

  • props/$emit

  • $parent / $children

  • $ref

2、非父子组件传值方式

  • 事件总线
//原理上就是建立一个公共的js文件,专门用来传递消息
//bus.js
import Vue from 'vue'
exports default new Vue
//需要传递消息的引入
import bus from './bus.js'  //在两个传值的组件引入
//传递消息
bus.$emit('msg',val)   //传值的组件
//接收消息
bus.$emit('msg',val => {  //接收的组件
    console.log(val)
})
  • attrs /listeners
//解决多级组件间传值的问题
//$attr 将父组件中不包含props属性传值子组件,通常配合 interitAttrs 选项一起使用
//$listeners监听子组件中数据变化,传递个父组件

<m-parent :msga="a" :msgb="b" :msgc="c"></m-parent> // app.vue
console.log('attrs',this.$attrs)    // 子组件 (得到app.vue的值)
<m-child v-bind="$attrs"></m-child>   // 父组件

3、vue-router

// 懒加载
{
    path: '/home',
    component: () => import('../views/Home.vue')
}
// 导航守卫
router.beforeEach((to, from, next) => {
  console.log(to.path)
  next()
})

4、Vuex

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {  //同步方法
    add (state) {
      state.count++
    },
    decrease (state) {
      state.count--
    }
  },
  actions: {  //同步/异步方法
    delayAdd (context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  },
  modules: {
  }
})
mutations //使用commit提交
actions //使用dispatch提交
  • vuex中的计算属性—Getters
store.js
getters: {
    doubleCount (state) {
        return state.count * 2
    }
},
demo.js
import { mapGetters } from 'vuex'
computed选项
// doubleCount(){
//   return this.$store.getters.doubleCount
// }
...mapGetters({
    doubleCount: 'douleCount'
}) 
  • 模块化概念—Modules

5、eslint覆盖默认配置

//eslint
'prettier/prettier': [
    'error',
    {
        semi: false,
        singleQuote: true,
        printWidth: 160
    }
]