首页 > 代码库 > Vue.js 2使用中的难点举例--子组件,slot, 动态组件,事件监听

Vue.js 2使用中的难点举例--子组件,slot, 动态组件,事件监听

一例打尽。。:)

<!DOCTYPE html><html>  <head>      <meta charset="UTF-8">      <title></title>      <link rel="stylesheet" href="http://www.mamicode.com/demo.css" />  </head>  <body>  <div id="app">    <ul>      <li @click="currentView = ‘home‘" >Home</li>      <li @click="currentView = ‘list‘" >List</li>      <li @click="currentView = ‘detail‘" >Detail</li>    </ul>    <keep-alive>      <component :is="currentView"></component>    </keep-alive>    <br/>    <component :is="currentView"></component>    <br/><br/>    <my-slot>      <p slot="title"> {{title}}</p>      <div slot="content"> {{ content}} </div>    </my-slot>    <br/><br/>    <comp-a></comp-a>    <comp-b></comp-b>  </div>     </body>  <script src="http://cdn.bootcss.com/vue/2.2.4/vue.min.js"></script>  <script>    Vue.component(‘my-slot‘, {      template: <div>         <div class="title">           <slot name="title"></slot>         </div>         <div class="content">           <slot name="content"></slot>         </div>       </div>    })    var bus = new Vue();    var vm = new Vue({      el: "#app",      data: {        currentView: ‘home‘,        title: "This is a title",        content: "This is the content"      },      components: {        home: {          template: <div>             <p>Home</p>             <ul>             <li v-for="item in items"> {{ item }} </li>             </ul>           </div>,          data: function() {            return {              items: []            }          },          active: function(done) {            var that = this;            setTimeout(function() {              that.items = [1, 2, 3, 4, 5];              done();            }, 1000)          }        },        list: {          template: ‘<div>List</div>‘        },        detail: {          template: ‘<div>Detail</div>‘        },        compA: {          template: <div>             <input type="text" v-model="name" />             <button @click="create">增加</button>             </div>,          data: function() {            return {              a: ""            }          },          methods: {            create: function() {              bus.$emit(‘create‘, {name: this.name});              this.name=‘‘;            }          }         },        compB: {          template: <ul>             <li v-for="item in items">{{ item.name }} </li>             </ul>,          data: function() {            return {              items: []            }          },          mounted() {            var that = this;            bus.$on(‘create‘, function(data){              that.items.push(data);            })          }        }      }    })    </script></html>

技术分享

Vue.js 2使用中的难点举例--子组件,slot, 动态组件,事件监听