vue 组件递归,非父子间组件通信简单实例

来源:互联网 发布:linux 虚拟ip 编辑:程序博客网 时间:2024/05/21 04:42

          VUE虽说相比于其他两大框架来说简单易上手些,但文档中仍是有些例子有点简单,下面就写出组件递归和非父子组件通信以供大家参考。

      组件递归:         

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>递归组件简单实例</title></head><script src="https://unpkg.com/vue/dist/vue.js"></script><body>    <div id="app">        <div>Hello Summmer</div>        <span>Number:</span>        <exa-ecomponent :number="0"></exa-ecomponent>    </div>    <script type="text/javascript">        Vue.component('exa-ecomponent', {            name: 'exa-ecomponent',            template: '<span><span>{{number}}</span><exa-ecomponent :number="number+1" v-if="currentNum"></exa-ecomponent></span>',            props: ['number'],            computed: {                currentNum: function () {                    return this.number < 10                }            }        })        new Vue({            el: '#app'        })    </script></body></html>
  
       非父子间组件通信:          
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>非父子间组件通信简单实例</title></head><script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script><body>    <div id="app">        <component-a></component-a>        <component-b></component-b>    </div></body><script>    var bus = new Vue() //首先建立一个空的Vue实例作为事件的中转    Vue.component('component-a', {        template: `<div><button @click="incrementB">{{masgA}}</button></div>`, //添加点击事件        data() {            return {                masgA: 0            }        },        methods: {            incrementB: function () {                bus.$emit('incrementB')            }        },        mounted: function () {            var _this = this            bus.$on('incrementA', function () {                _this.masgA++            })            bus.$on('incrementA', function () {                this.masgA++            })        }    })    Vue.component('component-b', {        template: `<div><button @click="incrementA">{{masgB}}</button></div>`,        data() {            return {                masgB: 0            }        },        methods: {            incrementA: function () {                bus.$emit('incrementA')            }        },        mounted: function () {            bus.$on('incrementB', function {                this.masgB++            })        }    })    var vm = new Vue({        el: "#app"    })</script>

  例子中已经很清楚的描述用法,如有不懂的地方,欢迎留言交流~

            

          

原创粉丝点击