服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue 组件注册全解析

Vue 组件注册全解析

2021-12-14 16:18风都散了…… JavaScript

这篇文章主要介绍了Vue 组件注册全解析的相关资料,帮助大家更好的理解和使用vue,感兴趣的朋友可以了解下

全局组件注册语法

components中的两个参数组件名称和组件内容

?
1
2
3
4
Vue.component(组件名称, {
   data: 组件数据,
   template:组件模板内容
  })

全局组件注册应用

组件创建:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Vue.component('button-counter', {
   data: function(){
    return {
     count: 0
    }
   },
   template: '<button @click="handle">点击了{{count}}次</button>',
   methods: {
    handle: function(){
     this.count ++;
    }
   }
  })
  var vm = new Vue({
   el: '#app',
   data: {
   }
  });

如何在页面中运用,直接在页面中应用组件名称

?
1
2
3
<div id="app">
  <button-counter></button-counter>
</div>

这个组件是可以重用的,直接在页面中多次使用,切数据相互独立,互不干扰

组件注册注意事项

1.data必须是一个函数

  • 分析函数与普通对象的对比

2.组件模板内容必须是单个根元素

  • 分析演示实际的效果

3.组件模板内容可以是模板字符串

  • 模板字符串需要浏览器提供支持(ES6语法)

4.组件命名方式

  • 短横线方式
?
1
Vue.component('my-component',{/*...*/})

驼峰方式

?
1
Vue.component('MyComponent',{/*...*/})

如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件,但是在普通的标签模板中,必须使用短横线的方式使用组件

局部组件

局部组件只能在注册它的父组件中使用

局部组件注册语法

?
1
2
3
4
5
6
7
8
9
10
11
var ComponentA = {/*...*/}
var ComponentB = {/*...*/}
var ComponentC = {/*...*/}
new Vue({
  el : '#app',
  components: {
    'component-a' : ComponentA,
    'component-b' : ComponentB,
    'component-c' : ComponentC
  }
})

组件的创建

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Vue.component('test-com',{
   template: '<div>Test<hello-world></hello-world></div>'
  });
  var HelloWorld = {
   data: function(){
    return {
     msg: 'HelloWorld'
    }
   },
   template: '<div>{{msg}}</div>'
  };
  var HelloTom = {
   data: function(){
    return {
     msg: 'HelloTom'
    }
   },
   template: '<div>{{msg}}</div>'
  };
  var HelloJerry = {
   data: function(){
    return {
     msg: 'HelloJerry'
    }
   },
   template: '<div>{{msg}}</div>'
  };
  var vm = new Vue({
   el: '#app',
   data: {
    
   },
   components: {
    'hello-world': HelloWorld,
    'hello-tom': HelloTom,
    'hello-jerry': HelloJerry
   }
  });

页面中的应用

?
1
2
3
4
5
6
<div id="app">
  <hello-world></hello-world>
  <hello-tom></hello-tom>
  <hello-jerry></hello-jerry>
  <test-com></test-com>
 </div>

以上就是Vue 组件注册全解析的详细内容,更多关于Vue 组件注册的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/limu-zy/p/14146563.html

延伸 · 阅读

精彩推荐