跟着文档学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>vue基础4(组件)</title>
  <!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> -->
  <script src="vue.js"></script>
</head>
<style>
</style>
<body>
  <div id="app">
    <h2>1.因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。</h2>
    <button-counter></button-counter>
    <article-title v-for='item in titles' :key='item.id' :title="item.title"></article-title>
    <h2>通过事件向父级组件发送消息</h2>
    <div :style="{ fontSize: postFontSize + 'em' }">
      <speak-parent v-for='item in titles' :key='item.id' :title="item.title"  v-on:enlarge-text="postFontSize += 0.1"></speak-parent>      
    </div>
    <h2>组件中使用v-model</h2>
    <custom-input v-model="searchText"></custom-input>
    <div>{{searchText}}</div>
    <h2>插槽</h2>
    <alert-box>
      Something bad happened.
    </alert-box>
  </div>
  
  <script>
    // 定义一个名为 button-counter 的新组件
    // 一个组件本质上是一个拥有预定义选项的一个 Vue 实例【注:组件要定义在创建实例Vue之前】,props完成父子组件间的通信
    // 所有的 Vue 组件都是 Vue 实例,并且接受相同的选项对象(data,computed,watch,methods,生命周期等)
    // 组件注册会有全局注册和局部注册(②)
    Vue.component('button-counter', {
      // data必须是一个函数,这样每个实例可以维护一份被返回对象的独立的拷贝(① what??????)
      data: function () {
        return {
          count: 0
        }
      },
      //不好意思报错了
      // data: {
      //   count: 0
      // },
      // 模板中必须只有一个根元素
      template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
    });
    Vue.component('article-title', {
      props: ['title'],
      template: '<h2>{{title}}</h2>'
    });
    // 通过事件向父级组件发送消息
    Vue.component('speak-parent', {
      props: ['title'],
      // 调用内建的 $emit 方法并传入事件的名字,来向父级组件触发一个事件
      template: `
        <div>
          <div>{{title}}</div>
          <button v-on:click="$emit('enlarge-text')">改变字号</button>
        </div>
      `
    });
    Vue.component('custom-input', {
      props: ['value'],
      template: `
        <input
          v-bind:value="value"
          v-on:input="$emit('input', $event.target.value)"
        >
      `
    });
    // 插槽
    Vue.component('alert-box', {
      template: `
        <div class="demo-alert-box">
          <strong>Error!</strong>
          <slot></slot>
        </div>
      `
    });
    var app = new Vue({
      el: '#app',
      data: {
        titles: [
          {id: '1', title: '我是第一'},
          {id: '2', title: '我是第二'},
          {id: '3', title: '我是第三'}
        ],
        postFontSize: 1,
        searchText: ''
      }
    });
  </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/cxuer/p/9070960.html