状态管理Bus的使用

2019-05-20  本文已影响0人  YM雨蒙

Bus

1. 父子组件之间通信

// src/components/AInput.vue

<template>
  <input @input="handlerInput" :value="value"/>
</template>
  
<script>
  export default {
    name: 'AInput',
    props: {
      value: {
        type: [String, Number],
        default: ''
      }
    },
    methods: {
      handlerInput (e) {
        const value = e.target.value
        this.$emit('input', value)  // 触发 input 事件, 传递 value
      }
    }
  }
</script>
// src/views/store.vue

<template>
  <div>
    <a-input v-model="inputValue"></a-input>  // 双向绑定 语法糖
  </div>
</template>
  
<script>
  import AInput from '_c/AInput.vue'
  export default {
    name: 'store',
    components: {
      AInput
    },
    data () {
      return {
        inputValue: ''
      }
    }
  }
</script>

2. 兄弟之间传值

// src/components/AShow.vue

<template>
  <div>
    {{ content }}
  </div>
</template>
  
<script>
  export default {
    name: 'AShow',
    props: {
      content: {
        type: [String, Number],
        default: ''
      }
    }
  }
</script>
// src/views/store.vue

<template>
  <div>
    <a-input @input="handlerInput" /> // 双向绑定 语法糖
    <a-show :content="inputValue" />
  </div>
</template>
  
<script>
  import AInput from '_c/AInput.vue'
  import AShow from '_c/AShow.vue'
  export default {
    name: 'store',
    components: {
      AInput,
      AShow
    },
    data () {
      return {
        inputValue: ''
      }
    },
    methods: {
      handlerInput (val) {
        this.inputValue = val
      }
    }
  }
</script>
// src/bus/index.js

import Vue from 'vue'
const Bus = new Vue()
export default Bus
// src/main.js

import Bus from './bus'
Vue.prototype.$bus = Bus  // 全局注册到根实例
// src/views/email.vue

<template>
    <div>
        <button @click="handlerClick">按我</button>
    </div>
</template>

<script>
    export default {
        methods: {
            handlerClick () {
                this.$bus.$emit('on-click', 'hello world')
            }
        }
    }
</script>
<template>
    <div>
        {{ message }}
    </div>
</template>

<script>
    export default {
        data () {
            return {
                message: ''
            }
        },
        mounted () {
            this.$bus.$on('on-click', mes => {
                this.message = mes
            })
        }
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读