重中之重的就是组件之间数据传递的几种形式
Vue2最常见的11种组件间的通信形式

  1. props
  2. $emit / v-on
  3. .sync
  4. v-model
  5. ref(获取子组件的属性和调用子组件办法)实质就是获取到子组件的this
  6. $children / $parent(获取子组件(不包含顺孙组件)的数组 / 获取父组件的this)
  7. $attrs / $listeners($attrs子组件外面获取父组件传递的属性,$listeners子组件获取父组件自定义的办法(这个自定义办法是子组件通过$emit传递过来的))
  8. provide / inject
  9. EventBus
  10. Vuex
  11. $root(获取根组件的,new Vue外面定义的办法和属性)
  12. Slot
  13. 公布订阅(pubsub-js)
  14. 本地存储(localstorage和sessionstorage)
    props
    父组件向子组件传送数据,这应该是最罕用的形式了
    子组件接管到数据之后,不能间接批改父组件的数据。
    否则会报错,因为当父组件从新渲染时,数据会被笼罩。如果只在子组件内要批改的话举荐应用 computed
    // Parent.vue 传送
    <template>
    <child :msg="msg"></child>
    </template>
    // Child.vue 接管
    export default {
    // 写法一 用数组接管
    props:['msg'],
    // 写法二 用对象接管,能够限定接管的数据类型、设置默认值、验证等 props:{
    msg:{

       type:String,   default:'这是默认数据'

    }
    },
    mounted(){
    console.log(this.msg)
    },
    }
    .sync 子组件能够批改父组件内容
    .sync能够帮咱们实现父组件向子组件传递的数据的双向绑定,所以子组件接管到数据后能够间接批改,并且会同时批改父组件的数据
    // Parent.vue
    <template>
    <child :page.sync="page"></child>
    </template>
    <script>
    export default {
    data(){

     return {     page:1 }

    }
    }
    // Child.vue
    export default {
    props:["page"],
    computed(){

     // 当咱们在子组件里批改 currentPage 时,父组件的 page 也会随之扭转        currentPage {     get(){         return this.page     },     set(newVal){         this.$emit("update:page", newVal)     } }

    }
    }</script>
    v-model
    和 .sync 相似,能够实现将父组件传给子组件的数据为双向绑定,子组件通过 $emit 批改父组件的数据
    // Parent.vue
    <template>
    <child v-model="value"></child>
    </template>
    <script>
    export default {
    data(){

     return {     value:1 }

    }
    }
    // Child.vue
    <template>
    <input :value="value" @input="handlerChange">
    </template>
    export default {
    props:["value"],
    // 能够批改事件名,默认为 input model:{

     event:"updateValue"

    },
    methods:{

     handlerChange(e){     this.$emit("input", e.target.value)     // 如果有下面的重命名就是这样     this.$emit("updateValue", e.target.value) }

    }
    }</script>
    ref
    ref 如果在一般的DOM元素上,援用指向的就是该DOM元素;
    如果在子组件上,援用的指向就是子组件实例;
    父组件能够通过 ref 被动获取子组件的属性或者调用子组件的办法
    // Child.vue
    export default {
    data(){

     return {     name:"oldCode" }

    },
    methods:{

     someMethod(msg){     console.log(msg) }

    }
    }
    // Parent.vue
    <template>
    <child ref="child"></child>
    </template>
    <script>
    export default {
    mounted(){

     const child = this.$refs.child console.log(child.name)  child.someMethod("调用了子组件的办法")

    }
    }</script>
    $emit / v-on
    子组件通过派发事件的形式给父组件数据,或者触发父组件更新等操作
    // Child.vue 派发
    export default {
    data(){
    return { msg: "这是发给父组件的信息" }
    },
    methods: {
    handleClick(){

       this.$emit("sendMsg",this.msg)

    }
    },
    }// Parent.vue 响应
    <template>
    <child v-on:sendMsg="getChildMsg"></child>
    // 或 简写
    <child @sendMsg="getChildMsg"></child>
    </template>
    export default {
    methods:{

     getChildMsg(msg){     console.log(msg) // 这是父组件接管到的音讯        }

    }
    }
    $attrs / $listeners
    多层嵌套组件传递数据时,如果只是传递数据,而不做两头解决的话就能够用这个,比方父组件向孙子组件传递数据时
    $attrs:蕴含父作用域里除 class 和 style 除外的非 props 属性汇合。通过 this.$attrs 获取父作用域中所有符合条件的属性汇合,而后还要持续传给子组件外部的其余组件,就能够通过 v-bind="$attrs"
    $listeners:蕴含父作用域里 .native 除外的监听事件汇合。如果还要持续传给子组件外部的其余组件,就能够通过 v-on="$linteners"应用形式是雷同的
    // Parent.vue
    <template>
    <child :name="name" title="1111" ></child>
    </template
    export default{
    data(){

     return {     name:"oldCode" }

    }
    }
    // Child.vue
    <template>
    // 持续传给孙子组件
    <sun-child v-bind="$attrs"></sun-child>
    </template>
    export default{
    props:["name"], // 这里能够接管,也能够不接管 mounted(){

     // 如果props接管了name 就是 { title:1111 },否则就是{ name:"oldCode", title:1111 } console.log(this.$attrs)

    }
    }
    $children / $parent
    $children:获取到一个蕴含所有子组件(不蕴含孙子组件)的 VueComponent 对象数组,能够间接拿到子组件中所有数据和办法等
    $parent:获取到一个父节点的 VueComponent 对象,同样蕴含父节点中所有数据和办法等
    // Parent.vue
    export default{
    mounted(){

     this.$children[0].someMethod() // 调用第一个子组件的办法 this.$children[0].name // 获取第一个子组件中的属性    }

    }
    // Child.vue
    export default{
    mounted(){

     this.$parent.someMethod() // 调用父组件的办法 this.$parent.name // 获取父组件中的属性    }

    }
    provide / inject
    provide / inject 是依赖注入,在一些插件或组件库里被罕用
    provide:能够让咱们指定想要提供给后辈组件的数据或办法
    inject:在任何后辈组件中接管想要增加在这个组件上的数据或办法,不论组件嵌套多深都能够间接拿来用
    要留神的是 provide 和 inject 传递的数据不是响应式的,也就是说用 inject 接管来数据后,provide 里的数据扭转了,后辈组件中的数据不会扭转,除非传入的就是一个可监听的对象 所以倡议还是传递一些常量或者办法
    // 父组件
    export default{
    // 办法一 不能获取 methods 中的办法 provide:{

     name:"oldCode", age: this.data中的属性

    },
    // 办法二 不能获取 data 中的属性 provide(){

     return {     name:"oldCode",     someMethod:this.someMethod // methods 中的办法        }

    },
    methods:{

     someMethod(){     console.log("这是注入的办法") }

    }
    }
    // 后辈组件
    export default{
    inject:["name","someMethod"],
    //或者
    inject: { foo: { from: 'bar', default: 'foo' } },
    mounted(){

     console.log(this.name) this.someMethod()

    }
    }
    EventBus
    EventBus 是地方事件总线,不论是父子组件,兄弟组件,跨层级组件等都能够应用它实现通信操作
    定义形式有三种
    // 办法一
    // 抽离成一个独自的 js 文件 Bus.js ,而后在须要的中央引入
    // Bus.js
    import Vue from "vue"
    export default new Vue()
    // 办法二 间接挂载到全局
    // main.js
    import Vue from "vue"
    Vue.prototype.$bus = new Vue()
    // 办法三 注入到 Vue 根对象上
    // main.js
    import Vue from "vue"new Vue({
    el:"#app",
    data:{

     Bus: new Vue()

    }
    })
    应用如下,以办法一按需引入为例
    // 在须要向内部发送自定义事件的组件内
    <template>
    <button @click="handlerClick">按钮</button>
    </template>
    import Bus from "./Bus.js"
    export default{
    methods:{

     handlerClick(){     // 自定义事件名 sendMsg     Bus.$emit("sendMsg", "这是要向内部发送的数据") }

    }
    }
    // 在须要接管内部事件的组件内
    import Bus from "./Bus.js"
    export default{
    mounted(){

     // 监听事件的触发 Bus.$on("sendMsg", data => {     console.log("这是接管到的数据:", data) })

    },
    beforeDestroy(){

     // 勾销监听 Bus.$off("sendMsg")

    }
    }
    Vuex 在大我的项目中被罕用
    Vuex 是状态管理器,集中式存储管理所有组件的状态。
    新建一个index.js文件, 里内容如下
    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from './getters'
    import actions from './actions'
    import mutations from './mutations'
    import state from './state'
    import user from './modules/user'
    Vue.use(Vuex)
    const store = new Vuex.Store({
    modules: {
    user
    },
    getters,
    actions,
    mutations,
    state
    })
    export default store
    而后在 main.js 引入
    import Vue from "vue"
    import store from "./store"new Vue({
    el:"#app",
    store,
    render: h => h(App)
    })
    而后在须要的应用组件里
    import { mapGetters, mapMutations } from "vuex"
    export default{
    computed:{

     // 形式一 而后通过 this.属性名就能够用了 ...mapGetters(["引入getters.js里属性1","属性2"]) // 形式二 ...mapGetters("user", ["user模块里的属性1","属性2"])

    },
    methods:{

     // 形式一 而后通过 this.属性名就能够用了 ...mapMutations(["引入mutations.js里的办法1","办法2"]) // 形式二 ...mapMutations("user",["引入user模块里的办法1","办法2"])

    }
    }
    // 或者也能够这样获取this.$store.state.xxxthis.$store.state.user.xxx
    slot插槽
    就是把子组件的数据通过插槽的形式传给父组件应用,而后再插回来
    // Child.vue
    <template>
    <div>

     <slot :user="user"></slot>

    </div>
    </template>
    export default{
    data(){

     return {     user:{ name:"oldCode" } }

    }
    }
    // Parent.vue
    <template>
    <div>

     <child v-slot="slotProps">     {{ slotProps.user.name }} </child>

    </div>
    </template>
    公布订阅pubsub-js(react也应用)
    应用subpub插件实现
    音讯订阅=工夫监听
    办法:
    import PubSub from 'pubsub-js'
    mounted(){

    /* 订阅办法,音讯名称,匿名函数msg=音讯名(不可省略),index是你须要传递的参数 */ PubSub.subscribe('delData',(msg,index)=>{    this.renwu.splice(index,1) });

    },
    接管组件
    import PubSub from 'pubsub-js'

/ 音讯公布,触发音讯订阅里的逻辑 /
PubSub.publish('delData',this.index);