黄子涵

组件的复用

你可以将组件进行任意次数的复用:

<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>
<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件的复用</title>
  <script src="./vue.js"></script>
</head>

<body>
  <div id="components-demo">
    <button-counter></button-counter><br>
    <button-counter></button-counter><br>
    <button-counter></button-counter>
  </div>
  <script>
    Vue.component('button-counter', {
      data: function () {
        return {
          count: 0
        }
      },
      template: '<button v-on:click="count++">黄子涵告诉你点击了 {{ count }} 次。</button>'
    })
    var VM = new Vue({
      el: '#components-demo'
    })
  </script>
</body>

</html>

image

注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。

data 必须是一个函数

当我们定义这个 <button-counter> 组件时,你可能会发现它的 data 并不是像这样直接提供一个对象:

data: {
  count: 0
}

取而代之的是,一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:

data: function () {
  return {
    count: 0
  }
}
<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件的复用</title>
  <script src="./vue.js"></script>
</head>

<body>
  <div id="components-demo">
    <button-counter></button-counter><br>
    <button-counter></button-counter><br>
    <button-counter></button-counter>
  </div>
  <script>
    Vue.component('button-counter', {
      data: {
        count: 0
      },
      template: '<button v-on:click="count++">黄子涵告诉你点击了 {{ count }} 次。</button>'
    })
    var VM = new Vue({
      el: '#components-demo'
    })
  </script>
</body>

</html>

如果 Vue 没有这条规则,点击一个按钮就可能会像如下代码一样影响到其它所有实例:

image

posted @ 2022-06-03 21:30  黄子涵  阅读(87)  评论(0编辑  收藏  举报