vue中通信方式

  • vuex中共享state
  • 父子组件emit/on
  • 跨组件event bus

跨组件eventbus通信

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
        <style>
            
        </style>
    </head>
    <body>
        <div id="todo-app">
            <h1>todo app</h1>
            <new-todo></new-todo>
            <todo-list></todo-list>
        </div>
    </body>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script type="text/javascript">
    var eventHub = new Vue({
        data() {
            return{
                todos:['A','B','C']
            }
        },
        created:function () {
            this.$on('add', this.addTodo)
            this.$on('delete', this.deleteTodo)
        },
        beforeDestroy:function () {
            this.$off('add', this.addTodo)
            this.$off('delete', this.deleteTodo)
        },
        methods: {
            addTodo: function (newTodo) {
                this.todos.push(newTodo)
            },
            deleteTodo: function (i) {this.todos.splice(i,1)
            }
        }
    })
    var newTodo={
        template: '<div><input type="text" autofocus v-model="newtodo"/><button @click="add">add</button></div>',
        data() {
            return { 
                newtodo: ''
            }
        },
        methods: {
            add: function(){
                eventHub.$emit('add',this.newtodo);
                this.newtodo='';
            }
        }
        
    }
    var todoList = {
        template:`<ul><li v-for="(index,item) in items">{{index}} \
          <button @click="rm(item)">X</button></li> \
          </ul>`,
        data(){
          return{
             items:eventHub.todos
          }
        },
        methods:{
          rm:function(i){
              eventHub.$emit('delete',i)
          }
        }
    }
    var app= new Vue({
        el:'#todo-app',
        components:{
            newTodo:newTodo,
            todoList:todoList
        }    
    })
    
         
    </script>
</html>

 

posted @ 2017-07-22 14:46  尹丹  阅读(260)  评论(0编辑  收藏  举报