vue组件间数据传递方式总结

209 阅读1分钟

1、props

props是单向数据传递,适用于父传子
parent.vue:
<template>
    <div class="hello">
    <h1>{{ msg }}</h1>
    <v-input  :info="msg"></v-input> 
    </div>
<script>
    import vInput from "./input.vue"
    export default {
      name: 'HelloWorld',
      data () {
        return {
          msg: 'Welcome to Your Vue.js App',
        }
      },
      components:{
        vInput
      }
    }
</script>
</template>
-----------------------------------------------------------------
chile.vue
<template>
    <div class="input-text">
        <div>{{info}}</div>
    </div>
</template>
<script>
export default {
    props:["info"]
}
</script>

2、自定义事件

parent.vue:
<template>
    <div class="parent">
        父组件 {{age}}
        <v-child @change="handle"></v-child>
    </div>
</template>
<script>
import vChild from "./child.vue"
export default {
    data(){
        return {
            age:20
        }
    },
    components:{
        vChild
    },
    methods:{
        handle(newage){
            this.age=newage
        }
    }
}
</script>
--------------------------------------------------------------
child.vue:
    <template>
        <div class="child">
            <button @click="increase">改变年龄</button>
            自组件{{newage}}
        </div>
    </template>
    
    <script>
    export default {
        data(){
            return {
                newage:20
            }
        },
        methods:{
            increase(){
                this.newage++
                this.$emit("change",this.newage)
            }
        }
    }
    </script>

3、父子组件间双向通信

props+自定义事件?

4、公交事件总线(bus)

eventBus.js:

    import Vue from 'vue';
    export default new Vue();
    
parent.vue:

child.vue:

5、vuex

TO_DO