Vue组件基础用法详解


Posted in Javascript onFebruary 05, 2020

Vue组件概述

组件(Component)是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。根据项目需求,抽象出一些组件,每个组件里包含了展现、功能和样式。每个页面,根据自己所需,使用不同的组件来拼接页面。这种开发模式使前端页面易于扩展,且灵活性高,而且组件之间也实现了解耦。

在 Vue 里,一个组件本质上是一个拥有预定义选项的一个 Vue 实例

组件是一个自定义元素或称为一个模块,包括所需的模板、逻辑和样式。在HTML模板中,组件以一个自定义标签的形式存在,起到占位符的功能。通过Vue.js的声明式渲染后,占位符将会被替换为实际的内容

下面是一个最简单的模块示例

<div id="app">
  <xiaohuochai></xiaohuochai>
</div>

Vue注册组件

组件注册包括全局注册和局部注册两种

全局注册

要注册一个全局组件,可以使用 Vue.component(tagName, options)

Vue.component('my-component', {
 // 选项
})

组件在注册之后,便可以在父实例的模块中以自定义元素 <my-component></my-component> 的形式使用

[注意]要确保在初始化根实例之前注册了组件

<div id="example">
 <my-component></my-component>
</div>
<script>
// 注册
Vue.component('my-component', {
 template: '<div>A custom component!</div>'
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

局部注册

通过使用组件实例选项components注册,可以使组件仅在另一个实例/组件的作用域中可用

<div id="example">
 <my-component></my-component>
</div>
<script>
// 注册
var Child = {
 template: '<div>A custom component!</div>'
};
// 创建根实例
new Vue({
 el: '#example',
  components: {
  // <my-component> 将只在父模板可用
  'my-component': Child
 } 
})
</script>

组件树

使用组件实例选项components注册,可以实现组件树的效果

<div id="example">
 <my-component></my-component>
</div>
<script>
// 注册
var headerTitle = {
  template: '<p>我是标题</p>',
};
var headerContent = {
  template: '<p>我是内容</p>',
};
var header = {
 template: `
   <div class="hd">
      <header-content></header-content>
      <header-title></header-title>
   </div>
 `,
  components: {
  'header-content': headerContent,
  'header-title': headerTitle
 }  
};
// 创建实例
new Vue({
 el: '#example',
  components: {
  'my-component': header
 } 
})
</script>

对于大型应用来说,有必要将整个应用程序划分为组件,以使开发可管理。一般地组件应用模板如下所示

<div id="app">
 <app-nav></app-nav>
 <app-view>
  <app-sidebar></app-sidebar>
  <app-content></app-content>
 </app-view>
</div>

v-once

尽管在 Vue 中渲染 HTML 很快,不过当组件中包含大量静态内容时,可以考虑使用 v-once 将渲染结果缓存起来

Vue.component('my-component', {
 template: '<div v-once>hello world!...</div>'
})

 

Vue组件的模板分离

在组件注册中,使用template选项中拼接HTML元素比较麻烦,这也导致了HTML和JS的高耦合性。庆幸的是,Vue.js提供了两种方式将定义在JS中的HTML模板分离出来

script

在script标签里使用 text/x-template 类型,并且指定一个 id

<script type="text/x-template" id="hello-world-template">
 <p>Hello hello hello</p>
</script>
Vue.component('hello-world', {
 template: '#hello-world-template'
})

上面的代码等价于

Vue.component('hello-world', {
 template: '<p>Hello hello hello</p>'
})

下面是一个简单示例

<div id="example">
 <my-component></my-component>
</div>
<script type="text/x-template" id="hello-world-template">
 <div>hello world!</div> 
</script>
<script>
Vue.component('my-component', {
 template: '#hello-world-template'
})
new Vue({
 el: '#example'
})
</script>

template

如果使用<template>标签,则不需要指定type属性

<div id="example">
 <my-component></my-component>
</div>
<template id="hello-world-template">
 <div>hello world!</div> 
</template>
<script>
// 注册
Vue.component('my-component', {
 template: '#hello-world-template'
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

 

Vue组件的命名约定

对于组件的命名,W3C规范是字母小写且包含一个中划线(-),虽然Vue没有强制要求,但最好遵循规范  

<!-- 在HTML模版中始终使用 kebab-case -->
<kebab-cased-component></kebab-cased-component>
<camel-cased-component></camel-cased-component>
<pascal-cased-component></pascal-cased-component>

当注册组件时,使用中划线、小驼峰、大驼峰这三种任意一种都可以

// 在组件定义中
components: {
 // 使用 中划线 形式注册
 'kebab-cased-component': { /* ... */ },
 // 使用 小驼峰 形式注册
 'camelCasedComponent': { /* ... */ },
 // 使用 大驼峰 形式注册
 'PascalCasedComponent': { /* ... */ }
}

 

Vue组件嵌套限制

并不是所有的元素都可以嵌套模板,因为要受到HTML元素嵌套规则的限制,尤其像<ul>,<ol>,<table>,<select> 限制了能被它包裹的元素,而一些像 <option> 这样的元素只能出现在某些其它元素内部

[注意]关于HTML标签的详细嵌套规则移步至此

在自定义组件中使用这些受限制的元素时会导致一些问题,例如

<table id="example">
 <my-row>...</my-row>
</table>

自定义组件 <my-row> 被认为是无效的内容,因此在渲染的时候会导致错误

<script>
// 注册
var header = {
 template: '<div class="hd">我是标题</div>' 
};
// 创建实例
new Vue({
 el: '#example',
  components: {
  'my-row': header
 } 
})
</script>

is属性

 变通的方案是使用特殊的 is 属性

<table id="example">
 <tr is="my-row"></tr>
</table>
<script>
// 注册
var header = {
 template: '<div class="hd">我是标题</div>'
};
// 创建实例
new Vue({
 el: '#example',
  components: {
  'my-row': header
 } 
})
</script>

 

Vue组件的根元素

Vue强制要求每一个Vue实例(组件本质上就是一个Vue实例)需要有一个根元素

如下所示,则会报错

<div id="example">
 <my-component></my-component>
</div>
<script>
// 注册
Vue.component('my-component', {
 template: `
  <p>第一段</p>
  <p>第二段</p>
 `,
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

需要改写成如下所示

<script>
// 注册
Vue.component('my-component', {
 template: `
  <div>
   <p>第一段</p>
   <p>第二段</p>
  </div> 
 `,
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

 

Vue组件数据传递

一般地,我们在Vue实例对象或Vue组件对象中,我们通过data来传递数据

<div id="example">
 <my-component></my-component>
 <my-component></my-component>
 <my-component></my-component>
</div>
<script>
// 注册
Vue.component('my-component', {
 template: '<div>{{message}}</div>',
 data:{
   message: 'hello'
 }
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

运行上面的代码,会使Vue停止执行,并在控制台发出错误提示,告诉你在组件中 data 必须是一个函数

可以用如下方式来绕开Vue的错误提示

<script>
// 注册
var data = {counter: 0}
Vue.component('my-component', {
 template: '<button v-on:click="counter += 1">{{ counter }}</button>',
 data:function(){
   return data;
 }
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

由于这三个组件共享了同一个 data,因此增加一个 counter 会影响所有组件

当一个组件被定义, data 需要声明为返回一个初始数据对象的函数,因为组件可能被用来创建多个实例。如果 data 仍然是一个纯粹的对象,则所有的实例将共享引用同一个数据对象。通过提供 data 函数,每次创建一个新实例后,能够调用 data 函数,从而返回初始数据的一个全新副本数据对象

因此,可以通过为每个组件返回全新的 data 对象来解决这个问题: 

<script>
// 注册
Vue.component('my-component', {
 template: '<button v-on:click="counter += 1">{{ counter }}</button>',
 data:function(){
   return {counter: 0};
 }
})
// 创建根实例
new Vue({
 el: '#example'
})
</script>

现在每个 counter 都有它自己内部的状态了

 

Vue组件原生事件

有时候,可能想在某个组件的根元素上监听一个原生事件。直接使用v-bind指令是不生效的

<div id="example">
 <my-component @click="doTheThing"></my-component>
 <p>{{message}}</p>
</div>
<script>
Vue.component('my-component', {
 template: '<button>按钮</button>',
})
new Vue({
 el: '#example',
 data:{
  message:0
 },
 methods:{
  doTheThing(){
   this.message++;
  }
 }
})
</script>

可以使用 .native 修饰 v-on指令即可

<div id="example">
 <my-component @click.native="doTheThing"></my-component>
 <p>{{message}}</p>
</div>
<script>
Vue.component('my-component', {
 template: '<button>按钮</button>',
})
new Vue({
 el: '#example',
 data:{
  message:0
 },
 methods:{
  doTheThing(){
   this.message++;
  }
 }
})

更多关于Vue组件的使用方法请点击下面的相关链接

Javascript 相关文章推荐
使用TextRange获取输入框中光标的位
Oct 14 Javascript
JavaScript与DropDownList 区别分析
Jan 01 Javascript
jQuery事件绑定.on()简要概述及应用
Feb 07 Javascript
js原生appendChild的bug解决心得分享
Jul 01 Javascript
使用JS CSS去除IE链接虚线框的三种方法
Nov 14 Javascript
jQuery拖拽插件gridster使用指南
Apr 21 Javascript
javascript去除空格方法小结
May 21 Javascript
谈谈AngularJs中的隐藏和显示
Dec 09 Javascript
JS仿淘宝搜索框用户输入事件的实现
Jun 19 Javascript
在vue中使用Autoprefixed的方法
Jul 27 Javascript
vue使用prop可以渲染但是打印台报错的解决方式
Nov 13 Javascript
Vue路由守卫及页面登录权限控制的设置方法(两种)
Mar 31 Javascript
vue组件传值的实现方式小结【三种方式】
Feb 05 #Javascript
vue路由传参的基本实现方式小结【三种方式】
Feb 05 #Javascript
Vuex的API文档说明详解
Feb 05 #Javascript
如何实现iframe父子传参通信
Feb 05 #Javascript
JavaScript对象原型链原理详解
Feb 05 #Javascript
基于Vue的侧边目录组件的实现
Feb 05 #Javascript
Js视频播放器插件Video.js使用方法详解
Feb 04 #Javascript
You might like
PHP学习 运算符与运算符优先级
2008/06/15 PHP
6种php上传图片重命名的方法实例
2013/11/04 PHP
PHP include任意文件或URL介绍
2014/04/29 PHP
php中this关键字用法分析
2016/12/07 PHP
PHP中Laravel 关联查询返回错误id的解决方法
2017/04/01 PHP
如何利用预加载优化Laravel Model查询详解
2017/08/11 PHP
php中curl和soap方式请求服务超时问题的解决
2018/06/11 PHP
PHP mongodb操作类定义与用法示例【适合mongodb2.x和mongodb3.x】
2018/06/16 PHP
javascript textContent与innerText的异同分析
2010/10/22 Javascript
jquery使用ColorBox弹出图片组浏览层实例演示
2013/03/14 Javascript
Js日期选择器并自动加入到输入框中示例代码
2013/08/02 Javascript
加载列表时jquery获取ul中第一个li的属性
2014/11/02 Javascript
js实现Select列表各项上移和下移的方法
2015/08/14 Javascript
AngularJS入门教程之AngularJS模型
2016/04/18 Javascript
浅析上传头像示例及其注意事项
2016/12/14 Javascript
js输入框使用正则表达式校验输入内容的实例
2017/02/12 Javascript
详解Vue.js分发之作用域槽
2017/06/13 Javascript
angular2+node.js express打包部署的实战
2017/07/27 Javascript
利用ES6的Promise.all实现至少请求多长时间的实例
2017/08/28 Javascript
使用Node.js实现ORM的一种思路详解(图文)
2017/10/24 Javascript
[59:00]DOTA2-DPC中国联赛 正赛 Ehome vs PSG.LGD BO3 第一场 3月7日
2021/03/11 DOTA
python 通过 socket 发送文件的实例代码
2018/08/14 Python
Django REST framework视图的用法
2019/01/16 Python
Pytorch中的variable, tensor与numpy相互转化的方法
2019/10/10 Python
有关Tensorflow梯度下降常用的优化方法分享
2020/02/04 Python
Pandas时间序列:时期(period)及其算术运算详解
2020/02/25 Python
太阳镜仓库,售价20美元或更少:Sunglass Warehouse
2016/09/28 全球购物
资深财务管理人员自我评价
2013/09/22 职场文书
求职简历推荐信范文
2013/12/02 职场文书
年度评优评先方案
2014/06/03 职场文书
早读课迟到检讨书
2014/09/25 职场文书
2014年煤矿工人工作总结
2014/12/08 职场文书
公证处委托书
2015/01/28 职场文书
幼儿园小班个人总结
2015/02/12 职场文书
nginx里的rewrite跳转的实现
2021/03/31 Servers
输入框跟随文字内容适配宽实现示例
2022/08/14 Javascript