饥人谷技术博客

01 怎么理解Vue中的组件?

2019-11-02  本文已影响0人  PingerL

Q1:什么是组件?

组件是可复用的Vue实例,且带有一个名字(内心os:不就是可重复使用的Vue实例么...)

Q2: 为什么要使用组件?

为了提高代码的复用性 (内心os: 这应该和函数封装是一个道理吧....)

Vue组件示例

  <!-- html中的内容,把 my-component 这个组件作为自定义元素来使用-->
  <div id="component-demo">
      <my-component></my-component>
  </div>
  <script>
// 定义一个名为 my-component 的新组件
     Vue.component('my-component',{
      data: function(){
        return {
          count: 0
        }
      },
      template: ' <button v-on:click="count++">你点击了{{count}}次</button>'
    })
// 我们可以在一个通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用:
    new Vue({el:'#component-demo'})
  </script>

总结:

  1. 注册一个自定义的组件
  2. 通过 new Vue创建 Vue 实例,并将实例挂载到DOM上
  3. 在对应的 html 中将自定义的组件作为自定义元素来使用

Q3: 组件只有注册了才能被Vue识别,那组件注册的类型有哪些呢?

有两种组件注册类型:局部注册和全局注册

<div id="app">
    <my-comp></my-comp>
</div>

 Vue.component('my-comp',{
       template:'<h3>我是新出炉的组件</h3>'
    })

 new Vue({
      el: "#app",
      data: {

      }
    })
  <div id="app">
    <my-comp></my-comp>
  </div>

  new Vue({
    el: "#app",
    components:{
        'my-comp':{template:'<h3>我是新出炉的组件</h3>'}
    },
    data: {

    }
  })

Q4: 组件的名字有什么讲究么?

答案是当然有了

Vue.component('my-component-name', { /* ... */ })

组件使用的奇淫技巧

  1. 推荐使用小写字母加­进行命名(必须) child, my­componnet命名组件
  2. template中的内容必须被一个DOM元素包括 ,也可以嵌套
  3. 在组件的定义中,除了template之外的其他选项—data,computed,methods
  4. data必须是一个方法
上一篇 下一篇

猜你喜欢

热点阅读