关于vue.js:Vue-组件注册方式

5次阅读

共计 1725 个字符,预计需要花费 5 分钟才能阅读完成。

全局注册

  • 全局注册的组件在注册后能够用于任意实例或组件中。
  • 留神:全局注册必须设置在根 Vue 实例创立之前

    Vue.component('组件名',{ /** 选项对象 */})

    例如

    Vue.component('my-component',{template:'<div> 全局组件 </div>'})
    new Vue({
    el:"#app",
    data:{}})
    <div id="app">
    <my-component><my-component>
    </div>

    组件根底

  • 实质上,组件是可复用的 Vue 实例,所以它们可与 new Vue 接管雷同的选项, 例如datamethod 以及 生命周期钩子 等。
  • 仅有的例外是像 el 这样根实例特有的选项。
  • 组件根底中次要解说:组件命名规定,template 选项,data 选项
  1. 组件命名规定(创立组件时的设置规定)

    • kebab-case:”my-component”
    • PascalCase:”MyComponent”

留神: 无论采纳哪种命名形式,在 DOM 中都只有 kebab-case 能够应用。

Vue.component('my-component-a',{template:'<div> 全局组件 </div>'})
Vue.component('MyComponentB',{template:'<div> 全局组件 </div>'})
<div id="app">
  <my-component-a></my-component-a>  // ok
  <my-component-b></my-component-b> // ok
  <MyComponentB></MyComponentB> // error 会认为残缺的一个单词
</div>
  1. template 选项

    • template 选项用于设置组件的构造,最终被引入根实例或其余组件中。
    • 模板中语法与根实例中构造统一,能够执行 vue 相干指令操作,插值表达式等
    • template 只能有一个根元素

      Vue.component("MyComponentA",{
      template:`
       <div>
       <h3> 组件 A 的题目内容 {{1+2*3}}</h3>
       </div>
      `
      })
  2. data 选项

    • data 选项用于存储组件的数据,与根实例不同,组件的 data 选项必须为函数,数据设置在返回值对象中。
    • 组件并不一定是单个呈现(一个组件一个性能的封装),为了确保多个组件实例内的数据是互相独立的而不是共用的,须要通过作用域隔离
    • 函数外部领有独立作用域,函数屡次调用,造成多个外部独立作用域,作用域内数据不会相互影响
    • 这种实现形式是为了确保每个组件实例能够保护一份被返回对象的独立的拷贝,不会相互影响。

      Vue.component("MyComA",{
      template:`
       <div>
       <h3> {{title}} </h3>
       <p> {{content}} </p>
       </div>
      `,
      data:function(){
       return {
         title:'题目',
         content:'内容'
       }
      }
      })

每个组件都是独立的,批改某个组件实例数据,其余不会被影响

部分注册

  • 部分注册的组件只能用在以后实例或组件中。
  • 留神 DOM 写法永远 kebab-case
  • components 内组件 键名是 kebab-case 带连字符要加引号

    new Vue({
    ...
    components:{
      'my-component-a':{template:'<div>{{ title}}</div>'
        data(){return { title:"a title 内容"}
        }
      },
      'MyComponentB':{template:'<div>{{ title}}</div>'
        data(){return { title:"b title 内容"}
        }
      }
    }
    })
    <div id="app">
    <my-component-a></my-component-a>  // ok
    <my-component-b></my-component-b> // ok
    </div>
  • 部分注册形式 2:独自配置组件选项对象

    var MyComA = { } // 将选项对象放在对象中
    var MyComB = { }
    
    new Vue({
    el:"#app",
    components:{
      'my-com-a':MyComA,
      MyComB:MyComB // ES6 简写成 MyComB
    }
    })
正文完
 0