1. 程式人生 > >跟著文檔學Vue(三)——組件基礎

跟著文檔學Vue(三)——組件基礎

ont err -s fontsize itl IE alert -i -a

<!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>

跟著文檔學Vue(三)——組件基礎