1. 程式人生 > 其它 >VUE學習二十,元件初步component

VUE學習二十,元件初步component

一、先看下面的程式碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
    <button-counter title="title1 : " @clicknow="clicknow"
> <h2>hi...h2</h2> </button-counter> <button-counter title="title2 : "></button-counter> </div> <script type="text/javascript"> Vue.component('button-counter', { props: ['title'], data: function () { return { count: 0 } }, template:
'<div><h1>hi...</h1><button v-on:click="clickfun">{{title}} You clicked me {{ count }} times.</button><slot></slot></div>', methods:{ clickfun : function () { this.count ++; this.$emit('clicknow', this.count); } } })
var vm = new Vue({ el : "#app", data : { }, methods:{ clicknow : function (e) { console.log(e); } } }); </script> <style type="text/css"> </style> </body> </html>

二、講解

1. 元件註冊

// 定義一個名為 button-counter 的新元件
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

2. 元件引用

<div id="components-demo">
  <button-counter></button-counter>
</div>
new Vue({ el: '#components-demo' })

3. 元件複用

<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

4 .data 必須是一個函式

data: function () {
  return {
    count: 0
  }
}

這樣,每個例項可以維護一份被返回物件的獨立的拷貝。

5 .通過 prop 向子元件傳遞資料

Vue.component('blog-post', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
})
<button-counter title="title2 : "></button-counter>

6.每個元件必須只有一個根元素

<div class="blog-post">
  <h3>{{ title }}</h3>
  <div v-html="content"></div>
</div>

7. 增加單擊事件

<button-counter title="title1 : " @clicknow="clicknow">
    methods:{
        clickfun : function () {
            this.count ++;
            this.$emit('clicknow', this.count);
        }
    }

8. 增加插槽slot

template: '<div><h1>hi...</h1><button v-on:click="clickfun">{{title}} You clicked me {{ count }} times.</button><slot></slot></div>',
    <button-counter title="title1 : " @clicknow="clicknow">
        <h2>hi...h2</h2>
    </button-counter>

本文參考:

https://cn.vuejs.org/v2/guide/components.html