1. 组件简介

  组件(Component)是 Vue.js 最强大的功能之一,组件可以扩展 HTML 元素,封装可重用的代码。

  组件:为了拆分Vue实例的代码量,以不同的组件来划分不同的功能模块,需要什么样的功能,可以去调用对应的组件。

  模块化和组件化的区别:

  ◊ 模块化:是从代码逻辑的角度进行划分的;方便代码分层开发,保证每个功能模块的职能单一。

  ◊ 组件化:是从UI界面的角度进行划分的;前端的组件化,方便UI组件的重用。  

2. 注册组件

  Vue.js提供两种组件注册方式:全局注册和局部注册。

2.1 全局组件

  全局注册需要在根实例初始化之前注册,这样组件才能在任意实例中被使用。

  注册全局组件语法格式:

Vue.component(tagName, options)

  其中,tagName 为组件名,options 为配置选项。

  这条语句需要写在var vm = new Vue({ options })之前。

  注册组件后调用方式:

<tagName></tagName>

  所有实例都能用全局组件。

  组件名定义方式:PascalCase和kebab-case。在组件命名时可以采用PascalCase或kebab-case,但在DOM中只能使用kebab-case。

  PascalCase示例:

<div id="app">
<my-component></my-component>
</div>
<script>
Vue.component('MyComponent', {
template: '<div>标题</div>'
}); var vm = new Vue({
el: "#app"
});
</script>

  kebab-case示例:

<div id="app">
<my-component></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<div>标题</div>'
}); var vm = new Vue({
el: "#app"
});
</script>
<div id="app">
<home></home>
</div>
<script>
Vue.component("home", {
template: "<div>{{text}}</div>",
data: function () {
return {
text: "主页"
};
}
}); new Vue({
el: "#app"
});
</script>
<div id="app">
<home></home>
</div>
<script>
var homeTpl = Vue.extend({ 
template: "<div>{{text}}</div>",
data: function () {
return {
text: "主页"
};
}
}); Vue.component('home', homeTpl); new Vue({
el: "#app"
});
</script>

  使用template标签:

<div id="app">
<home></home>
</div>
<template id="tpl">
<div>{{text}}</div>
</template>
<script>
Vue.component("home", {
template: "#tpl",
data: function () {
return {
text: "主页"
};
}
}); new Vue({
el: "#app"
});
</script>

2.2 局部组件

  局部组件只能在被注册的组件中使用,不能在其他组件中使用。

<div id="app">
<home></home>
</div>
<script>
new Vue({
el: "#app",
components: {
"home": {
template: "<div>{{text}}</div>",
data: function () {
return {
text: "主页"
};
}
}
}
});
</script>

2.3 Vue.extend

2.3.1 基本使用

<div id="app">
<home></home>
</div>
<script>
var home = Vue.extend({
template: "<div>标题</div>"
}); Vue.component("home", home); new Vue({
el: "#app"
});
</script>

2.3.2 参数data

  data:在 Vue.extend() 中必须是函数。

<body>
<task></task> <script>
var task = Vue.extend({
template:"<div>{{ taskName }}</div>",
data:function(){
return {
taskName:"任务名称"
}
}
}); new task().$mount("task");
</script>
</body>

2.3.3 使用$mount

  在实例中没有el选项时,可通过mount挂载。

  mount:挂载,将vue实例挂靠在某个dom元素上的一个过程。

<!DOCTYPE html>
<html> <head>
<meta charset="utf-8">
<title>libing.vue</title>
<script src="node_modules/vue/dist/vue.min.js"></script>
</head> <body>
<div id="app"></div>
<script>
var home = Vue.extend({
template: "<div>标题</div>"
}); new home().$mount("#app");
</script>
</body> </html>

3. 组件通信

3.1 props:父组件向子组件传递数据

  prop 是组件用来传递数据的自定义特性,在组件上注册自定义属性。

  prop特性注册成为组件实例的属性。

   props :父组件向子组件传递数据。

  一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。

3.1.1 静态props

  示例:

<div id="app">
<home text="主页"></home>
</div>
<script>
var homeTpl = Vue.extend({
props:["text"],
template: "<div>{{text}}</div>"
}); Vue.component('home', homeTpl); new Vue({
el: "#app"
});
</script>

3.1.2 动态props

  使用 v-bind 动态绑定 props 的值到父组件的数据中。每当父组件的数据变化时,该变化也会传导给子组件。

<div id="app">
<home v-bind:text="text"></home>
</div>
<script>
var homeTpl = Vue.extend({
props: ["text"],
template: "<div>{{text}}</div>"
}); Vue.component('home', homeTpl); new Vue({
el: "#app",
data: {
text: "主页"
}
});
</script>

  由于HTML Attribute不区分大小写,当使用DOM模板时,camelCase的props名称要转为kebab-case。

<div id="app">
<home warning-text="提示信息"></home>
</div>
<script>
Vue.component('home', {
props: ['warningText'],
template: '<div>{{ warningText }}</div>'
}); var vm = new Vue({
el: "#app"
});
</script>

  传递的数据可以是来自父级的动态数据,使用指令v-bind来动态绑定props的值,当父组件的数据变化时,也会传递给子组件。

<div id="app">
<home v-bind:warning-text="warningText"></home>
</div>
<script>
Vue.component('home', {
props: ['warningText'],
template: '<div>{{ warningText }}</div>'
}); var vm = new Vue({
el: "#app",
data: {
warningText: '提示信息'
}
});
</script>

注:prop 是单向传递,当父组件的属性变化时,将传递给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态。

  示例:

<template>
<li>{{ id }}-{{ text }}</li>
</template>
<script>
export default {
name: "TodoItem",
props: ["id", "text"]
};
</script>

TodoItem.vue

<template>
<ul>
<TodoItem
v-for="item in list"
:key="item.id"
:id="item.id"
:text="item.text"
></TodoItem>
</ul>
</template>
<script>
import TodoItem from "./TodoItem"; export default {
name: "TodoList",
components: {
TodoItem
},
data: function() {
return {
list: [
{
id: 1,
text: "To Do"
},
{
id: 2,
text: "In progress"
},
{
id: 3,
text: "Done"
}
]
};
}
};
</script>

TodoList.vue

<template>
<div id="app">
<TodoList />
</div>
</template> <script>
import TodoList from './views/TodoList' export default {
name: 'App',
components: {
TodoList
}
}
</script>

App.vue

3.1.3 props验证

  为组件的 prop 指定验证要求,如果有一个需求没有被满足,则 Vue 会在控制台中警告。

Vue.component('my-component', {
props: {
// 基础的类型检查 (`null` 匹配任何类型)
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组且一定会从一个工厂函数返回默认值
default: function () {
return {
message: 'hello'
}
}
},
// 自定义验证函数
propF: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
});

  类型检查:type可以是下列原生构造函数中的一个:String、Number、Boolean、Array、Object、Date、Function、Symbol,也可以是一个自定义的构造函数,并且通过 instanceof 来进行检查确认。

  示例:

<div id="app">
<parent-component></parent-component>
</div> <template id="child-component1">
<h2>{{ message }}</h2>
</template>
<template id="child-component2">
<h2>{{ message }}</h2>
</template>
<template id="parent-component">
<div>
<child-component1></child-component1>
<child-component2></child-component2>
</div>
</template> <script>
Vue.component('parent-component', {
template: '#parent-component',
components: {
'child-component1': {
template: '#child-component1',
data() {
return {
message: '子组件1'
};
}
},
'child-component2': {
template: '#child-component2',
data() {
return {
message: '子组件2'
};
}
}
}
}); var vm = new Vue({
el: "#app"
});
</script>

  示例:

<div id="app">
<todo :todo-data="taskList"></todo>
</div> <template id="tpl-todo-item">
<li>{{ id }} - {{ text }}</li>
</template> <template id="tpl-todo-list">
<ul>
<todo-item v-for="item in todoData" :id="item.id" :text="item.text"></todo-item>
</ul>
</template> <script>
// 构建一个子组件
var todoItem = Vue.extend({
template: "#tpl-todo-item",
props: {
id: {
type: Number,
required: true
},
text: {
type: String,
default: ''
}
}
}) // 构建一个父组件
var todoList = Vue.extend({
template: "#tpl-todo-list",
props: {
todoData: {
type: Array,
default: []
}
},
// 局部注册子组件
components: {
todoItem: todoItem
}
}) // 注册到全局
Vue.component('todo', todoList) new Vue({
el: "#app",
data: {
taskList: [{
id: 1,
text: 'New'
},
{
id: 2,
text: 'InProcedure'
},
{
id: 3,
text: 'Done'
}
]
}
});
</script>

3.2 自定义事件:子组件向父组件传递数据

  每一个Vue实例都实现事件接口:

  $on(eventName):监听事件

  $emit(eventName) :触发事件,自定义事件。推荐始终使用 kebab-case 的事件名。

  子组件需要向父组件传递数据时,子组件用$emit(eventName)来触发事件,父组件用$on(eventName)来监听子组件的事件。

  示例1:

<template>
<div>
<button @click="onparent">子组件触发父组件</button>
</div>
</template>
<script>
export default {
methods: {
onparent() {
this.$emit("onchild");
}
}
};
</script>

Child.vue

<template>
<div>
<Child @onchild="inparent"></Child>
</div>
</template>
<script>
import Child from "./Child";
export default {
components: {
Child
},
methods: {
inparent() {
console.log("父组件响应了");
}
}
};
</script>

Parent.vue

<template>
<div id="app">
<Parent />
</div>
</template> <script>
import Parent from './views/Parent' export default {
name: 'App',
components: {
Parent
}
}
</script>

App.vue

  示例2:

<div id="app">
<searchbar></searchbar>
</div> <template id="tpl-search-form">
<div class="input-group form-group" style="width: 500px;">
<input type="text" class="form-control" placeholder="请输入查询关键字" v-model="keyword" />
<span class="input-group-btn">
<input type="button" class="btn btn-primary" value="查询" @click="search">
</span>
</div>
</template>
<template id="tpl-search-bar">
<searchform @onsearch="search"></searchform>
</template> <script>
// 构建一个子组件
var searchform = Vue.extend({
template: "#tpl-search-form",
data: function () {
return {
keyword: 'libing'
};
},
methods: {
search: function () {
this.$emit('onsearch', this.keyword);
}
}
}); // 构建一个父组件
var searchbar = Vue.extend({
template: "#tpl-search-bar",
components: {
searchform: searchform
},
methods: {
search(keyword) {
console.log(keyword);
}
}
}) // 注册到全局
Vue.component('searchbar', searchbar); new Vue({
el: "#app"
});
</script>

  购物车示例:

<div id="app">
<shoppingcart :shopppingcarts="products" @calc="getTotal"></shoppingcart>
<div>总计:{{ totalPrice }}</div>
</div>
<template id="shoppingcart">
<table>
<tr>
<th>商品ID</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
</tr>
<tr v-for="item in shopppingcarts">
<td>{{ item.ID }}</td>
<td>{{ item.ProductName }}</td>
<td>{{ item.UnitPrice }}</td>
<td><input type="text" v-model="item.Quantity" @change="calcTotal" /></td>
</tr>
</table>
</template>
<script>
var shoppingcart = Vue.extend({
template: "#shoppingcart",
props: ["shopppingcarts"],
methods: {
calcTotal: function () {
this.$emit("calc");
}
}
}); new Vue({
el: "#app",
components: {
shoppingcart: shoppingcart
},
data: {
totalPrice: 100,
products: [{
ID: 1,
ProductName: "手机",
UnitPrice: 1000,
Quantity: 2
}, {
ID: 2,
ProductName: "电脑",
UnitPrice: 5000,
Quantity: 5
}]
},
methods: {
getTotal() {
console.log(new Date());
this.totalPrice = 0;
this.products.forEach(product => {
this.totalPrice += product.UnitPrice * product.Quantity;
});
}
},
mounted() {
//当vue执行完毕之后,去执行函数
this.getTotal();
}
});
</script>

3.3 EventBus:非父子组件通信

  非父子组件包括:兄弟组件、跨级组件。

  通过实例化一个Vue对象 (如:const bus = new Vue() ) 作为总线,在组件中通过事件传递参数( bus.$emit(event, [...args]) ),再在其他组件中通过bus来监听此事件并接受参数( bus.$on(event, callback) ),从而实现通信。

  示例:

  bus.js

import Vue from 'vue'

const bus = new Vue();

export default bus;

  Send.vue

<template>
<div class="send">
<h1>发送参数:{{msg}}</h1>
<button @click="send">发送</button>
</div>
</template>
<script>
import bus from "../utils/bus.js"; export default {
data() {
return {
msg: "Hello World"
};
},
methods: {
send() {
bus.$emit("receive", this.msg);
}
}
};
</script>

  Receive.vue

<template>
<div class="receive">
<h1>接收参数:{{msg}}</h1>
</div>
</template>
<script>
import bus from "../utils/bus.js"; export default {
data() {
return {
msg: "Hello"
};
},
created() {
bus.$on("receive", param => {
this.msg = param;
});
},
beforeDestroy() {
bus.$off("receive");
}
};
</script>

  App.vue

<template>
<div id="app">
<Send></Send>
<Receive></Receive>
</div>
</template> <script>
import Send from './views/Send'
import Receive from './views/Receive' export default {
name: 'App',
components: {
Send,
Receive
}
}
</script>

Vue.js 2.x笔记:组件(5)的更多相关文章

  1. 两万字Vue.js基础学习笔记

    Vue.js学习笔记 目录 Vue.js学习笔记 ES6语法 1.不一样的变量声明:const和let 2.模板字符串 3.箭头函数(Arrow Functions) 4. 函数的参数默认值 5.Sp ...

  2. 基于Vue.js的表格分页组件

    有一段时间没更新文章了,主要是因为自己一直在忙着学习新的东西而忘记分享了,实在惭愧. 这不,大半夜发文更一篇文章,分享一个自己编写的一个Vue的小组件,名叫BootPage. 不了解Vue.js的童鞋 ...

  3. Vue.js的表格分页组件

    转自:http://www.cnblogs.com/Leo_wl/p/5522299.html 有一段时间没更新文章了,主要是因为自己一直在忙着学习新的东西而忘记分享了,实在惭愧. 这不,大半夜发文更 ...

  4. 从零开始学习Vue.js,学习笔记

    一.为什么学习vue.js methods 只有纯粹的数据逻辑,而不是去处理 DOM 事件细节. vue.js兼具angular.js和react的优点,并且剔除了他们的缺点 官网:http://cn ...

  5. vue.js应用开发笔记

    看vue.js有几天了,之前也零零散散的瞅过,不过一直没有动手去写过demo,这几天后台事比较少,一直在讨论各种需求(其实公司对需求还是比较重视与严谨的,一个项目需求讨论就差不多一周了,这要搁之前,天 ...

  6. vue.js初学,笔记1,安装

    最近学习vue.js,下面是笔记: 说明:因为npm安装插件是从国外服务器下载,受网络影响大,可能出现异常,如果npm的服务器在中国就好了,所以我们乐于分享的淘宝团队干了这事.来自官网:"这 ...

  7. 基于 Vue.js 的移动端组件库mint-ui实现无限滚动加载更多

    通过多次爬坑,发现了这些监听滚动来加载更多的组件的共同点, 因为这些加载更多的方法是绑定在需要加载更多的内容的元素上的, 所以是进入页面则直接触发一次,当监听到滚动事件之后,继续加载更多, 所以对于无 ...

  8. vue.js中的全局组件和局部组件

    组件(Component)是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能. 组件的使用有三 ...

  9. Vue.js 2.x笔记:状态管理Vuex(7)

    1. Vuex简介与安装 1.1 Vuex简介 Vuex是为vue.js应用程序开发的状态管理模式,解决的问题: ◊ 组件之间的传参,多层嵌套组件之间的传参以及各组件之间耦合度过高问题 ◊ 不同状态中 ...

随机推荐

  1. logistic逻辑回归公式推导及R语言实现

    Logistic逻辑回归 Logistic逻辑回归模型 线性回归模型简单,对于一些线性可分的场景还是简单易用的.Logistic逻辑回归也可以看成线性回归的变种,虽然名字带回归二字但实际上他主要用来二 ...

  2. 2.1命令行和JSON的配置「深入浅出ASP.NET Core系列」

    希望给你3-5分钟的碎片化学习,可能是坐地铁.等公交,积少成多,水滴石穿,谢谢关注. 命令行配置 1.新建控制台项目 2.nuget引入microsoft.aspnetcore.all 这里要注意版本 ...

  3. springboot情操陶冶-web配置(九)

    承接前文springboot情操陶冶-web配置(八),本文在前文的基础上深入了解下WebSecurity类的运作逻辑 WebSecurityConfigurerAdapter 在剖析WebSecur ...

  4. 1分钟解决VS每次运行都显示“正在还原nuget程序包”问题

    VS一直停留在“正在还原nuget程序包” 在开发中,运行不同版本的vs会显示还原nuget程序包,还原需要不短的时间,并且不一定还原成功. 或者其他什么原因导致需要还原nuget程序包,这样很烦的有 ...

  5. RAC(ReactiveCocoa)概括

    ReactiveCocoa(简称RAC,以下都用RAC)是github团队开源的一套基于Cocoa并且具有FRP(Functional Reactive Programming-响应式编程)特性的框架 ...

  6. Redis 小白指南(二)- 聊聊五大类型:字符串、散列、列表、集合和有序集合

    Redis 小白指南(二)- 聊聊五大类型:字符串.散列.列表.集合和有序集合 引言 开篇<Redis 小白指南(一)- 简介.安装.GUI 和 C# 驱动介绍>已经介绍了 Redis 的 ...

  7. 前端面试知识点集锦(JavaScript篇)

    目录 1.谈谈你对Ajax的理解?(概念.特点.作用) 2.说说你对延迟对象deferred的理解? 3.什么是跨域,如何实现跨域访问? 4.为什么要使用模板引擎? 5.JavaScript是一门什么 ...

  8. element表格添加序号

    表格代码:黄色部分为序号列关键代码上图: <el-table :data="tableData" border height="480" style=&q ...

  9. web服务器负载均衡与集群基本概念一

    Web集群是由多个同时运行同一个web应用的服务器组成,在外界看来就像一个服务器一样,这多台服务器共同来为客户提供更高性能的服务.集群更标准的定义是:一组相互独立的服务器在网络中表现为单一的系统,并以 ...

  10. APP网站安全漏洞检测服务的详细介绍

    01)概述: 关于APP漏洞检测,分为两个层面的安全检测,包括手机应用层,以及APP代码层,与网站的漏洞检测基本上差不多,目前越来越多的手机应用都存在着漏洞,关于如何对APP进行漏洞检测,我们详细的介 ...