Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue 组件通信 #16

Open
5Mi opened this issue Jun 9, 2016 · 0 comments
Open

vue 组件通信 #16

5Mi opened this issue Jun 9, 2016 · 0 comments

Comments

@5Mi
Copy link
Owner

5Mi commented Jun 9, 2016

先记录下个 小注意点
click

<div class="pop-btnBox">
    <!-- 此处事件为touched由于和父组件触发按钮太近,若为click的话一瞬间有时会触发click事件 导致popup出现又立刻消失(闪屏)-->
    <input type="button":class='["cancel-btn"]'value="取消"     @touchend="handleClose"/>
</div>

正题

vue中父子组件通信

父子通信

  • props

    默认单向 强制双向用.sync绑定修饰符
    子组件中设置props属性

        //子组件中
        export default{
            props:["items"]
        }
    

    父组件中向子组件标签里动态传值

        <child :items="something"></child>
    
  • Object.assign

    在父组件中 将引入的子组件对象进行合并

    ...
    import {popup} from './components/popup.vue';
    //父组件中
    export default{
        data(){
            return{
                test:1
            }
        },
        methods:{
            handle(){
                let tran_test = this.test;
                let mypopup = Object.assign(popup,{
                    data:{
                        something = tran_test;
                    }
                });
                let vuemypopup = new Vue(mypopup);
                vuemypopup.$on('someevent',(resp)=>{
                    //callback
                });
                vuemypopup.$mount().$append("body");
            }
        }
        ...
    }
    
  • costume event

  • 使用 $on() 监听事件;
  • 使用 $emit() 在它上面触发事件;
  • 使用 $dispatch() 派发事件,事件沿着父链冒泡;
  • 使用 $broadcast()广播事件,事件向下传导给所有的后代。
  • 不同于 DOM事件,Vue事件在冒泡过程中第一次触发回调之后自动停止冒泡,除非回调明确返回 true。

官方示例

<!-- 子组件模板 -->
<template id="child-template">
  <input v-model="msg">
  <button v-on:click="notify">Dispatch Event</button>
</template>

<!-- 父组件模板 -->
<div id="events-example">
  <p>Messages: {{ messages | json }}</p>
  <child></child>
</div>
// 注册子组件
// 将当前消息派发出去
Vue.component('child', {
  template: '#child-template',
  data: function () {
    return { msg: 'hello' }
  },
  methods: {
    notify: function () {
      if (this.msg.trim()) {
        this.$dispatch('child-msg', this.msg)
        this.msg = ''
      }
    }
  }
})

// 初始化父组件
// 将收到消息时将事件推入一个数组
var parent = new Vue({
  el: '#events-example',
  data: {
    messages: []
  },
  // 在创建实例时 `events` 选项简单地调用 `$on`
  events: {
    'child-msg': function (msg) {
      // 事件回调内的 `this` 自动绑定到注册它的实例上
      this.messages.push(msg)
    }
  }
})
  • Vuex store

    state,mutations,actions,getters

    通信组件共用store共享状态

这三种

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant