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

posted @ 2021-07-09 08:09  那些年的事儿  阅读(58)  评论(0编辑  收藏  举报