vue 组件

作者: Elvmx | 来源:发表于2019-02-12 23:36 被阅读157次

    什么是组件?

    组件是可复用的 Vue 实例。

    为什么要使用组件?

    使用组件能将项目按功能模块或页面层级拆分得更细小,更易于维护。

    组件的定义分为几种?

    两种

    1. 全局注册
    2. 局部注册

    如何全局注册组件

    使用 Vue.component 方法

        Vue.component('hello', {
          data: function() {
            return {
              msg: '张三'
            }
          },
          template: `
            <div>{{ msg }}</div>
          `
        })
    

    如何局部注册组件

    在需要使用这个组件的组件中或根实例中,使用 components 选项

        new Vue({
          el: '#app',
          components: {
            helloWorld: {
              data: function() {
                return {
                  msg: '张三'
                }
              },
              template: `
                <div>{{ msg }}</div>
              `
            }
          }
        })
    

    如何使用组件

    把组件的名字作为自定义元素来使用即可

    PS

    1. 组件的名称不要与现有标签或现有组件重名
    2. 组件的 template 选项需要有一个根元素,且只能有一个根元素
    3. 组件的 data 选项需要时一个函数,在函数中返回一个对象
    4. 全局注册组件,必须写在 new Vue 之前
    5. 如果组件的名字是 驼峰 命名方式,那么使用的时候需要为 短横线 方式
      new Vue({
        el: '#app',
        components: {
          helloWorld: {
            data: function() {
              return {
                msg: '张三'
              }
            },
            template: `
              <div>{{ msg }}</div>
            `
          }
        }
      })
    
      <div id="app">
        <hello-world></hello-world>  
      </div>
    
    1. 上面的第五点中,如果使用组件的时候是在如下的环境中,则可以不用。

    相关文章

      网友评论

        本文标题:vue 组件

        本文链接:https://www.haomeiwen.com/subject/qzvleqtx.html