文章列表


Vue间组件通信之findComponents

<p><span style="text-wrap: nowrap;">Vue中组件间通信的方法:provide / inject 和 dispatch / broadcast。它们有各自的使用场景和局限,比如前者多用于子组件获取父组件的状态,后者常用于父子组件间通过自定义事件通信。</span><br/></p><p><span style="text-wrap: nowrap;">本文将介绍第 3 种组件通信方法,也就是 findComponents 系列方法,它并非 Vue.js 内置,而是需要自行实现,以工具函数的形式来使用,它是一系列的函数,可以说是组件通信的终极方案。</span></p><p><span style="text-wrap: nowrap;">findComponents 系列方法最终都是返回组件的实例,进而可以读取或调用该组件的数据和方法。</span></p><p><span style="text-wrap: nowrap;">它适用于以下场景:</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;由一个组件,向上找到最近的指定组件;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;由一个组件,向上找到所有的指定组件;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;由一个组件,向下找到最近的指定组件;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;由一个组件,向下找到所有指定的组件;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;由一个组件,找到指定组件的兄弟组件。</span></p><p><span style="text-wrap: nowrap;">5 个不同的场景,对应 5 个不同的函数,实现原理也大同小异。</span></p><p><strong><span style="text-wrap: nowrap;">实现</span></strong></p><p><span style="text-wrap: nowrap;">5 个函数的原理,都是通过递归、遍历,找到指定组件的 `name` 选项匹配的组件实例并返回。</span><span style="text-wrap: nowrap;">在目录 `src` 下新建文件夹 `utils` 用来放置工具函数,并新建文件 `assist.js`,本文所有函数都在这个文件里完成,每个函数都通过 `export` 对外提供(如果你不了解 export,请查看扩展阅读)</span></p><p><span style="text-wrap: nowrap;">向上找到最近的指定组件——findComponentUpward</span><br/></p><p><span style="text-wrap: nowrap;">先看代码:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;assist.js //&nbsp;由一个组件,向上找到最近的指定组件 function&nbsp;findComponentUpward&nbsp;(context,&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;let&nbsp;parent&nbsp;=&nbsp;context.$parent; &nbsp;&nbsp;let&nbsp;name&nbsp;=&nbsp;parent.$options.name; &nbsp;&nbsp;while&nbsp;(parent&nbsp;&amp;&amp;&nbsp;(!name&nbsp;||&nbsp;[componentName].indexOf(name)&nbsp;&lt;&nbsp;0))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;parent&nbsp;=&nbsp;parent.$parent; &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(parent)&nbsp;name&nbsp;=&nbsp;parent.$options.name; &nbsp;&nbsp;} &nbsp;&nbsp;return&nbsp;parent; } export&nbsp;{&nbsp;findComponentUpward&nbsp;};</pre><p><span style="text-wrap: nowrap;">findComponentUpward 接收两个参数,第一个是当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 `this`;第二个参数是要找的组件的 `name` 。</span></p><p><span style="text-wrap: nowrap;">findComponentUpward 方法会在 while 语句里不断向上覆盖当前的 `parent` 对象,通过判断组件(即 parent)的 name 与传入的 componentName 是否一致,直到直到最近的一个组件为</span><br/></p><p><span style="text-wrap: nowrap;">止。</span></p><p><span style="text-wrap: nowrap;">与 dispatch 不同的是,findComponentUpward 是直接拿到组件的实例,而非通过事件通知组件。比如下面的示例,有组件 A 和组件 B,A 是 B 的父组件,在 B 中获取和调用 A 中的数据和</span><br/></p><p><span style="text-wrap: nowrap;">方法:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;component-a.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;A &nbsp;&nbsp;&nbsp;&nbsp;&lt;component-b&gt;&lt;/component-b&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;componentB&nbsp;from&nbsp;&#39;./component-b.vue&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentA&#39;, &nbsp;&nbsp;&nbsp;&nbsp;components:&nbsp;{&nbsp;componentB&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;Aresn&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sayHello&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(&#39;Hello,&nbsp;Vue.js&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt; &lt;!--&nbsp;component-b.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;B &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;{&nbsp;findComponentUpward&nbsp;}&nbsp;from&nbsp;&#39;../utils/assist.js&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentB&#39;, &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;comA&nbsp;=&nbsp;findComponentUpward(this,&nbsp;&#39;componentA&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(comA)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(comA.name);&nbsp;&nbsp;//&nbsp;Aresn &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;comA.sayHello();&nbsp;&nbsp;//&nbsp;Hello,&nbsp;Vue.js &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">使用起来很简单,只要在需要的地方调用 findComponentUpward 方法就行,第一个参数一般都是传入 this,即当前组件的上下文(实例)。</span></p><p><span style="text-wrap: nowrap;">上例的 comA,保险起见,加了一层 `if (comA)` 来判断是否找到了组件 A,如果没有指定的组件而调用的话,是会报错的。</span></p><p><span style="text-wrap: nowrap;">findComponentUpward 只会找到最近的一个组件实例,如果要找到全部符合要求的组件,就需要用到下面的这个方法。</span></p><p><span style="text-wrap: nowrap;"><strong>向上找到所有的指定组件——findComponentsUpward</strong></span></p><p><span style="text-wrap: nowrap;">代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;assist.js //&nbsp;由一个组件,向上找到所有的指定组件 function&nbsp;findComponentsUpward&nbsp;(context,&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;let&nbsp;parents&nbsp;=&nbsp;[]; &nbsp;&nbsp;const&nbsp;parent&nbsp;=&nbsp;context.$parent; &nbsp;&nbsp;if&nbsp;(parent)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(parent.$options.name&nbsp;===&nbsp;componentName)&nbsp;parents.push(parent); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;parents.concat(findComponentsUpward(parent,&nbsp;componentName)); &nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;[]; &nbsp;&nbsp;} } export&nbsp;{&nbsp;findComponentsUpward&nbsp;};</pre><p><span style="text-wrap: nowrap;">与 findComponentUpward 不同的是,findComponentsUpward 返回的是一个数组,包含了所有找到的组件实例(注意函数名称中多了一个“s”)。</span></p><p><span style="text-wrap: nowrap;">findComponentsUpward 的使用场景较少,一般只用在递归组件里面(后面小节会介绍),因为这个函数是一直向上寻找父级(parent)的,只有递归组件的父级才是自身。事实上,iView&nbsp;</span></p><p><span style="text-wrap: nowrap;">在使用这个方法也都是用在递归组件的场景,比如菜单组件 Menu。由于递归组件在 Vue.js 组件里面并不常用,那自然 findComponentsUpward 也不常用了。</span></p><p><span style="text-wrap: nowrap;"><strong>向下找到最近的指定组件——findComponentDownward</strong></span></p><p><span style="text-wrap: nowrap;">代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;assist.js //&nbsp;由一个组件,向下找到最近的指定组件 function&nbsp;findComponentDownward&nbsp;(context,&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;const&nbsp;childrens&nbsp;=&nbsp;context.$children; &nbsp;&nbsp;let&nbsp;children&nbsp;=&nbsp;null; &nbsp;&nbsp;if&nbsp;(childrens.length)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(const&nbsp;child&nbsp;of&nbsp;childrens)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;name&nbsp;=&nbsp;child.$options.name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(name&nbsp;===&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;children&nbsp;=&nbsp;child; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;children&nbsp;=&nbsp;findComponentDownward(child,&nbsp;componentName); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(children)&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &nbsp;&nbsp;return&nbsp;children; } export&nbsp;{&nbsp;findComponentDownward&nbsp;};</pre><p><span style="text-wrap: nowrap;">`context.$children` 得到的是当前组件的全部子组件,所以需要遍历一遍,找到有没有匹配到的组件 `name`,如果没找到,继续递归找每个 $children 的 $children,直到找到最近的一个为止。</span></p><p><span style="text-wrap: nowrap;">来看个示例,仍然是 A、B 两个组件,A 是 B 的父组件,在 A 中找到 B:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;component-b.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;B &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentB&#39;, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;Aresn&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sayHello&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(&#39;Hello,&nbsp;Vue.js&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt; &lt;!--&nbsp;component-a.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;A &nbsp;&nbsp;&nbsp;&nbsp;&lt;component-b&gt;&lt;/component-b&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;componentB&nbsp;from&nbsp;&#39;./component-b.vue&#39;; &nbsp;&nbsp;import&nbsp;{&nbsp;findComponentDownward&nbsp;}&nbsp;from&nbsp;&#39;../utils/assist.js&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentA&#39;, &nbsp;&nbsp;&nbsp;&nbsp;components:&nbsp;{&nbsp;componentB&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;comB&nbsp;=&nbsp;findComponentDownward(this,&nbsp;&#39;componentB&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(comB)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(comB.name);&nbsp;&nbsp;//&nbsp;Aresn &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;comB.sayHello();&nbsp;&nbsp;//&nbsp;Hello,&nbsp;Vue.js &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">示例中的 A 和 B 是父子关系,因此也可以直接用 `ref` 来访问,但如果不是父子关系,中间间隔多代,用它就很方便了。</span></p><p><strong><span style="text-wrap: nowrap;">向下找到所有指定的组件——findComponentsDownward</span></strong></p><p><span style="text-wrap: nowrap;">如果要向下找到所有的指定组件,要用到 findComponentsDownward 函数,代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;assist.js //&nbsp;由一个组件,向下找到所有指定的组件 function&nbsp;findComponentsDownward&nbsp;(context,&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;return&nbsp;context.$children.reduce((components,&nbsp;child)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(child.$options.name&nbsp;===&nbsp;componentName)&nbsp;components.push(child); &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;foundChilds&nbsp;=&nbsp;findComponentsDownward(child,&nbsp;componentName); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;components.concat(foundChilds); &nbsp;&nbsp;},&nbsp;[]); } export&nbsp;{&nbsp;findComponentsDownward&nbsp;};</pre><p><span style="text-wrap: nowrap;">这个函数实现的方式有很多,这里巧妙使用 `reduce` 做累加器,并用递归将找到的组件合并为一个数组并返回,代码量较少,但理解起来稍困难。</span></p><p><span style="text-wrap: nowrap;">用法与 findComponentDownward 大同小异,就不再写用例了。</span></p><p><strong><span style="text-wrap: nowrap;">找到指定组件的兄弟组件——findBrothersComponents</span></strong></p><p><span style="text-wrap: nowrap;">代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;assist.js //&nbsp;由一个组件,找到指定组件的兄弟组件 function&nbsp;findBrothersComponents&nbsp;(context,&nbsp;componentName,&nbsp;exceptMe&nbsp;=&nbsp;true)&nbsp;{ &nbsp;&nbsp;let&nbsp;res&nbsp;=&nbsp;context.$parent.$children.filter(item&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;item.$options.name&nbsp;===&nbsp;componentName; &nbsp;&nbsp;}); &nbsp;&nbsp;let&nbsp;index&nbsp;=&nbsp;res.findIndex(item&nbsp;=&gt;&nbsp;item._uid&nbsp;===&nbsp;context._uid); &nbsp;&nbsp;if&nbsp;(exceptMe)&nbsp;res.splice(index,&nbsp;1); &nbsp;&nbsp;return&nbsp;res; } export&nbsp;{&nbsp;findBrothersComponents&nbsp;};</pre><p><span style="text-wrap: nowrap;">相比其它 4 个函数,findBrothersComponents 多了一个参数 `exceptMe`,是否把本身除外,默认是 true。寻找兄弟组件的方法,是先获取 `context.$parent.$children`,也就是父组件的全</span></p><p><span style="text-wrap: nowrap;">部子组件,这里面当前包含了本身,所有也会有第三个参数 exceptMe。Vue.js 在渲染组件时,都会给每个组件加一个内置的属性 `_uid`,这个 \_uid 是不会重复的,借此我们可以从一系列兄弟</span></p><p><span style="text-wrap: nowrap;">组件中把自己排除掉。</span></p><p><span style="text-wrap: nowrap;">举个例子,组件 A 是组件 B 的父级,在 B 中找到所有在 A 中的兄弟组件(也就是所有在 A 中的 B 组件):</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;component-a.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;A &nbsp;&nbsp;&nbsp;&nbsp;&lt;component-b&gt;&lt;/component-b&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;componentB&nbsp;from&nbsp;&#39;./component-b.vue&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentA&#39;, &nbsp;&nbsp;&nbsp;&nbsp;components:&nbsp;{&nbsp;componentB&nbsp;} &nbsp;&nbsp;} &lt;/script&gt; &lt;!--&nbsp;component-b.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;B &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;{&nbsp;findBrothersComponents&nbsp;}&nbsp;from&nbsp;&#39;../utils/assist.js&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentB&#39;, &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;comsB&nbsp;=&nbsp;findBrothersComponents(this,&nbsp;&#39;componentB&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(comsB);&nbsp;&nbsp;//&nbsp;①&nbsp;[],空数组 &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">在 ① 的位置,打印出的内容为空数组,原因是当前 A 中只有一个 B,而 findBrothersComponents 的第三个参数默认是 true,也就是将自己除外。如果在 A 中再写一个 B:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;component-a.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;组件&nbsp;A &nbsp;&nbsp;&nbsp;&nbsp;&lt;component-b&gt;&lt;/component-b&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;component-b&gt;&lt;/component-b&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt;</pre><p><span style="text-wrap: nowrap;">这时就会打印出 `[VueComponent]`,有一个组件了,但要注意在控制台会打印两遍,因为在 A 中写了两个 B,而 `console.log` 是在 B 中定义的,所以两个都会执行到。如果你看懂了这里,</span></p><p><span style="text-wrap: nowrap;">那应该明白打印的两遍 `[VueComponent]`,分别是另一个 `&lt;component-b&gt;`(如果没有搞懂,要仔细琢磨琢磨哦)。</span></p><p><span style="text-wrap: nowrap;">如果将 B 中 findBrothersComponents 的第三个参数设置为 false:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;component-b.vue export&nbsp;default&nbsp;{ &nbsp;&nbsp;name:&nbsp;&#39;componentB&#39;, &nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;comsB&nbsp;=&nbsp;findBrothersComponents(this,&nbsp;&#39;componentB&#39;,&nbsp;false); &nbsp;&nbsp;&nbsp;&nbsp;console.log(comsB); &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">此时就会打印出 `[VueComponent, VueComponent]`,也就是包含自身了。</span></p><p><span style="text-wrap: nowrap;">以上就是 5 个函数的详细介绍,get 到这 5 个,以后就再也不用担心组件通信了。</span></p><p><br/></p><p><strong><span style="text-wrap: nowrap;">扩展阅读</span></strong></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;[ES6 Module 的语法](http://es6.ruanyifeng.com/#docs/module)</span><br/></p>

Vue实战篇:Form表单数据校验

<p><strong><span style="text-wrap: nowrap;">实战:具有数据校验功能的表单组件——Form</span></strong></p><p><span style="text-wrap: nowrap;">本文基于这组件间的通信方法,来实现一个具有数据校验功能的表单组件——Form。</span></p><p><strong><span style="text-wrap: nowrap;">Form 组件概览</span></strong></p><p><span style="text-wrap: nowrap;">表单类组件在项目中会大量使用,比如输入框(Input)、单选(Radio)、多选(Checkbox)、下拉选择器(Select)等。在使用表单类组件时,也会经常用到数据校验,如果每次都写校验程</span></p><p><span style="text-wrap: nowrap;">序来对每一个表单控件校验,会很低效,因此需要一个能够校验基础表单控件的组件,也就是本节要完成的 Form 组件。一般的组件库都提供了这个组件,比如 iView,它能够校验内置的 15 种</span></p><p><span style="text-wrap: nowrap;">控件,且支持校验自定义组件。</span></p><p><span style="text-wrap: nowrap;">Form 组件分为两个部分,一个是外层的 `Form` 表单域组件,一组表单控件只有一个 Form,而内部包含了多个 `FormItem` 组件,每一个表单控件都被一个 FormItem 包裹。基本的结构看起</span></p><p><span style="text-wrap: nowrap;">来像:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;i-form&gt; &nbsp;&nbsp;&lt;i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;form.name&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&lt;/i-form-item&gt; &nbsp;&nbsp;&lt;i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;form.mail&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&lt;/i-form-item&gt; &lt;/i-form&gt;</pre><p><span style="text-wrap: nowrap;">Form 要用到数据校验,并在对应的 FormItem 中给出校验失败的提示,校验我们会用到一个开源库[async-validator](</span><a href="https://github.com/yiminghe/async-validator)," style="text-wrap: nowrap;">https://github.com/yiminghe/async-validator),</a></p><p><span style="text-wrap: nowrap;"> 基本主流的组件库都是基于它做的校验。使用它很简单,只需按要求写好一个校验规则就好,比如:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">[ &nbsp;&nbsp;{&nbsp;required:&nbsp;true,&nbsp;message:&nbsp;&#39;邮箱不能为空&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;}, &nbsp;&nbsp;{&nbsp;type:&nbsp;&#39;email&#39;,&nbsp;message:&nbsp;&#39;邮箱格式不正确&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;} ]</pre><p><span style="text-wrap: nowrap;">这个代表要校验的数据先判断是否为空(required: true),如果为空,则提示“邮箱不能为空”,触发校验的事件为失焦(trigger: &#39;blur&#39;),如果第一条满足要求,再进行第二条的验证,判断</span></p><p><span style="text-wrap: nowrap;">是否为邮箱格式(type: &#39;email&#39;)等等,还支持自定义校验规则。更详细的用法可以参看它的文档。</span></p><p><strong><span style="text-wrap: nowrap;">接口设计</span></strong><br/></p><p><span style="text-wrap: nowrap;">我们先使用最新的 Vue CLI 3 创建一个空白的项目(如果你还不清楚 Vue CLI 3 的用法,需要先补习一下了,可以阅读文末的扩展阅读 1),并使用 `vue-router` 插件,同时安装好</span><br/></p><p><span style="text-wrap: nowrap;">&nbsp;`async-validator` 库。</span></p><p><span style="text-wrap: nowrap;">在 `src/components` 下新建一个 `form` 文件夹,并初始化两个组件 `form.vue` 和 `form-item.vue`,然后初始化项目,配置路由,创建一个页面能够被访问到。</span></p><p><span style="text-wrap: nowrap;">编写一个 Vue.js 组件,最重要的是设计好它的接口,一个 Vue.js 组件的接口来自三个部分:props、slots、events。而 Form 和 FormItem 两个组件主要做数据校验,用不</span></p><p><span style="text-wrap: nowrap;">到 events。Form 的 slot 就是一系列的 FormItem,FormItem 的 slot 就是具体的表单控件,比如输入框 `&lt;i-input&gt;` 。那主要设计的就是 props 了。</span></p><p><span style="text-wrap: nowrap;">在 `Form` 组件中,定义两个 props:</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;model:表单控件绑定的数据对象,在校验或重置时会访问该数据对象下对应的表单数据,类型为 Object。</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;rules:表单验证规则,即上面介绍的 async-validator 所使用的校验规则,类型为 Object。</span></p><p><span style="text-wrap: nowrap;">在 `FormItem` 组件中,也定义两个 props:</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;label:单个表单组件的标签文本,类似原生的 `&lt;label&gt;` 元素,类型为 String。</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;prop:对应表单域 Form 组件 model 里的字段,用于在校验或重置时访问表单组件绑定的数据,类型为 String。</span></p><p><span style="text-wrap: nowrap;">定义好 props,就可以写出大概的用例了:</span></p><p><br/></p><pre class="brush:js;toolbar:false">&lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form&nbsp;:model=&quot;formValidate&quot;&nbsp;:rules=&quot;ruleValidate&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form-item&nbsp;label=&quot;用户名&quot;&nbsp;prop=&quot;name&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;formValidate.name&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form-item&nbsp;label=&quot;邮箱&quot;&nbsp;prop=&quot;mail&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;formValidate.mail&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;iForm&nbsp;from&nbsp;&#39;../components/form/form.vue&#39;; &nbsp;&nbsp;import&nbsp;iFormItem&nbsp;from&nbsp;&#39;../components/form/form-item.vue&#39;; &nbsp;&nbsp;import&nbsp;iInput&nbsp;from&nbsp;&#39;../components/input/input.vue&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;components:&nbsp;{&nbsp;iForm,&nbsp;iFormItem,&nbsp;iInput&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;formValidate:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;&#39;, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mail:&nbsp;&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ruleValidate:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;required:&nbsp;true,&nbsp;message:&nbsp;&#39;用户名不能为空&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mail:&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;required:&nbsp;true,&nbsp;message:&nbsp;&#39;邮箱不能为空&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;type:&nbsp;&#39;email&#39;,&nbsp;message:&nbsp;&#39;邮箱格式不正确&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">有两点需要注意的是:</span></p><p><span style="text-wrap: nowrap;">1.&nbsp; 这里的 `&lt;i-input&gt;` 并不是原生的 `&lt;input&gt;` 输入框,而是一个特制的输入框组件,之后会介讲解的功能和代码;</span></p><p><span style="text-wrap: nowrap;">2.&nbsp; `&lt;i-form-item&gt;` 的属性 `prop` 是字符串,所以它前面没有冒号(即不是 `:prop=&quot;name&quot;`)。</span></p><p><span style="text-wrap: nowrap;">当前的两个组件只是个框框,还没有实现任何功能,不过万事开头难,定义好接口,剩下的就是补全组件的逻辑,而对于使用者,知道了 props、events、slots,就已经能写出上例的使用代码了</span><span style="text-wrap: nowrap;">到此,Form 和 FormItem 的代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;form.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;form&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;slot&gt;&lt;/slot&gt; &nbsp;&nbsp;&lt;/form&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;iForm&#39;, &nbsp;&nbsp;&nbsp;&nbsp;props:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;Object &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rules:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;Object &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;form-item.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;label&nbsp;v-if=&quot;label&quot;&gt;{{&nbsp;label&nbsp;}}&lt;/label&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;slot&gt;&lt;/slot&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/div&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;iFormItem&#39;, &nbsp;&nbsp;&nbsp;&nbsp;props:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;label:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default:&nbsp;&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;prop:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><strong><span style="text-wrap: nowrap;">在 Form 中缓存 FormItem 实例</span></strong></p><p><span style="text-wrap: nowrap;">`Form` 组件的核心功能是数据校验,一个 Form 中包含了多个 FormItem,当点击提交按钮时,要逐一对每个 FormItem 内的表单组件校验,而校验是由使用者发起,并通过 `Form` 来调用每</span><br/></p><p><span style="text-wrap: nowrap;">一个 `FormItem` 的验证方法,再将校验结果汇总后,通过 `Form` 返回出去。</span></p><p><span style="text-wrap: nowrap;">因为要在 Form 中逐一调用 FormItem 的验证方法,而 Form 和 FormItem 是独立的,需要预先将 FormItem 的每个实例缓存在 Form 中,这个操作就需要用到第 4 节的组件通信方法。当每个</span><br/></p><p><span style="text-wrap: nowrap;">FormItem 渲染时,将其自身(this)作为参数通过 `dispatch` 派发到 Form 组件中,然后通过一个数组缓存起来;同理当 FormItem 销毁时,将其从 Form 缓存的数组中移除。相关代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form-item.vue,部分代码省略 import&nbsp;Emitter&nbsp;from&nbsp;&#39;../../mixins/emitter.js&#39;; export&nbsp;default&nbsp;{ &nbsp;&nbsp;name:&nbsp;&#39;iFormItem&#39;, &nbsp;&nbsp;mixins:&nbsp;[&nbsp;Emitter&nbsp;], &nbsp;&nbsp;//&nbsp;组件渲染时,将实例缓存在&nbsp;Form&nbsp;中 &nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;如果没有传入&nbsp;prop,则无需校验,也就无需缓存 &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(this.prop)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iForm&#39;,&nbsp;&#39;on-form-item-add&#39;,&nbsp;this); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}, &nbsp;&nbsp;//&nbsp;组件销毁前,将实例从&nbsp;Form&nbsp;的缓存中移除 &nbsp;&nbsp;beforeDestroy&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iForm&#39;,&nbsp;&#39;on-form-item-remove&#39;,&nbsp;this); &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">注意,Vue.js 的组件渲染顺序是由内而外的,所以 FormItem 要先于 Form 渲染,在 FormItem 的 mounted 触发时,我们向 Form 派发了事件 `on-form-item-add`,并将当前 FormItem 的</span></p><p><span style="text-wrap: nowrap;">实例(this)传递给了 Form,而此时,Form 的 mounted 尚未触发,因为 Form 在最外层,如果在 Form 的 mounted 里监听事件,是不可以的,所以要在其 created 内监听自定义事件,</span></p><p><span style="text-wrap: nowrap;">Form 的 created 要先于 FormItem 的 mounted。所以 Form 的相关代码为:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;name:&nbsp;&#39;iForm&#39;, &nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fields:&nbsp;[] &nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;}, &nbsp;&nbsp;created&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-item-add&#39;,&nbsp;(field)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(field)&nbsp;this.fields.push(field); &nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-item-remove&#39;,&nbsp;(field)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(field.prop)&nbsp;this.fields.splice(this.fields.indexOf(field),&nbsp;1); &nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">定义的数据 `fields` 就是用来缓存所有 FormItem 实例的。</span></p><p><strong><span style="text-wrap: nowrap;">触发校验</span></strong><br/></p><p><span style="text-wrap: nowrap;">Form 支持两种事件来触发校验:</span><br/></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;**blur**:失去焦点时触发,常见的有输入框失去焦点时触发校验;</span><br/></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;**change**:实时输入时触发或选择时触发,常见的有输入框实时输入时触发校验、下拉选择器选择项目时触发校验等。</span></p><p><span style="text-wrap: nowrap;">以上两个事件,都是有具体的表单组件来触发的,我们先来编写一个简单的输入框组件 `i-input`。在 `components` 下新建目录 `input`,并创建文件 `input.vue`:</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;input.vue&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;input &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type=&quot;text&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:value=&quot;currentValue&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@input=&quot;handleInput&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@blur=&quot;handleBlur&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;Emitter&nbsp;from&nbsp;&#39;../../mixins/emitter.js&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;iInput&#39;, &nbsp;&nbsp;&nbsp;&nbsp;mixins:&nbsp;[&nbsp;Emitter&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;props:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default:&nbsp;&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;currentValue:&nbsp;this.value &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;watch:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value&nbsp;(val)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.currentValue&nbsp;=&nbsp;val; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleInput&nbsp;(event)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;value&nbsp;=&nbsp;event.target.value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.currentValue&nbsp;=&nbsp;value; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$emit(&#39;input&#39;,&nbsp;value); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iFormItem&#39;,&nbsp;&#39;on-form-change&#39;,&nbsp;value); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleBlur&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iFormItem&#39;,&nbsp;&#39;on-form-blur&#39;,&nbsp;this.currentValue); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">Input 组件中,绑定在 `&lt;input&gt;` 元素上的原生事件 `@input`,每当输入一个字符,都会调用句柄 `handleInput`,并通过 `dispatch` 方法向上级的 FormItem 组件派发自定义事件</span></p><p><span style="text-wrap: nowrap;">&nbsp;`on-form-change`;同理,绑定的原生事件 `@blur` 会在 input 失焦时触发,并传递事件 `on-form-blur`。</span></p><p><span style="text-wrap: nowrap;">基础组件有了,接下来要做的,是在 FormItem 中监听来自 Input 组件派发的自定义事件。这里可以在 mounted 中监听,因为你的手速远赶不上组件渲染的速度,不过在 created 中监听也是</span></p><p><span style="text-wrap: nowrap;">没任何问题的。相关代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form-item.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;setRules&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-blur&#39;,&nbsp;this.onFieldBlur); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-change&#39;,&nbsp;this.onFieldChange); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;}, &nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(this.prop)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iForm&#39;,&nbsp;&#39;on-form-item-add&#39;,&nbsp;this); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.setRules(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">通过调用 `setRules` 方法,监听表单组件的两个事件,并绑定了句柄函数 `onFieldBlur` 和 `onFieldChange`,分别对应 blur 和 change 两种事件类型。当 onFieldBlur 或 onFieldChange 函</span></p><p><span style="text-wrap: nowrap;">数触发时,就意味着 FormItem 要对**当前的数据**进行一次校验。当前的数据,指的就是通过表单域 Form 中定义的 props:model,结合当前 FormItem 定义的 props:prop 来确定的数据,</span></p><p><span style="text-wrap: nowrap;">可以回顾上文写过的用例。</span></p><p><span style="text-wrap: nowrap;">因为 FormItem 中只定义了数据源的某个 key 名称(即属性 prop),要拿到 Form 中 model 里的数据,需要用到第 3 节的通信方法 provide / inject。所以在 Form 中,把整个实例(this)向</span></p><p><span style="text-wrap: nowrap;">下提供,并在 FormItem 中注入:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;provide()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;form&nbsp;:&nbsp;this &nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;} } //&nbsp;form-item.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;inject:&nbsp;[&#39;form&#39;] }</pre><p><span style="text-wrap: nowrap;">准备好这些,接着就是最核心的校验功能了。blur 和 change 事件都会触发校验,它们调用同一个方法,只是参数不同。相关代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form-item.vue,部分代码省略 import&nbsp;AsyncValidator&nbsp;from&nbsp;&#39;async-validator&#39;; export&nbsp;default&nbsp;{ &nbsp;&nbsp;inject:&nbsp;[&#39;form&#39;], &nbsp;&nbsp;props:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;prop:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;}, &nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validateState:&nbsp;&#39;&#39;,&nbsp;&nbsp;//&nbsp;校验状态 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validateMessage:&nbsp;&#39;&#39;,&nbsp;&nbsp;//&nbsp;校验不通过时的提示信息 &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}, &nbsp;&nbsp;computed:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;从&nbsp;Form&nbsp;的&nbsp;model&nbsp;中动态得到当前表单组件的数据 &nbsp;&nbsp;&nbsp;&nbsp;fieldValue&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.form.model[this.prop]; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}, &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;从&nbsp;Form&nbsp;的&nbsp;rules&nbsp;属性中,获取当前&nbsp;FormItem&nbsp;的校验规则 &nbsp;&nbsp;&nbsp;&nbsp;getRules&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;formRules&nbsp;=&nbsp;this.form.rules; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;formRules&nbsp;=&nbsp;formRules&nbsp;?&nbsp;formRules[this.prop]&nbsp;:&nbsp;[]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;[].concat(formRules&nbsp;||&nbsp;[]); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;只支持&nbsp;blur&nbsp;和&nbsp;change,所以过滤出符合要求的&nbsp;rule&nbsp;规则 &nbsp;&nbsp;&nbsp;&nbsp;getFilteredRule&nbsp;(trigger)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;rules&nbsp;=&nbsp;this.getRules(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;rules.filter(rule&nbsp;=&gt;&nbsp;!rule.trigger&nbsp;||&nbsp;rule.trigger.indexOf(trigger)&nbsp;!==&nbsp;-1); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;/** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;校验数据 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;@param&nbsp;trigger&nbsp;校验类型 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;@param&nbsp;callback&nbsp;回调函数 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;validate(trigger,&nbsp;callback&nbsp;=&nbsp;function&nbsp;()&nbsp;{})&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;rules&nbsp;=&nbsp;this.getFilteredRule(trigger); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!rules&nbsp;||&nbsp;rules.length&nbsp;===&nbsp;0)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;设置状态为校验中 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validateState&nbsp;=&nbsp;&#39;validating&#39;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;以下为&nbsp;async-validator&nbsp;库的调用方法 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;descriptor&nbsp;=&nbsp;{}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;descriptor[this.prop]&nbsp;=&nbsp;rules; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;validator&nbsp;=&nbsp;new&nbsp;AsyncValidator(descriptor); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;model&nbsp;=&nbsp;{}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model[this.prop]&nbsp;=&nbsp;this.fieldValue; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validator.validate(model,&nbsp;{&nbsp;firstFields:&nbsp;true&nbsp;},&nbsp;errors&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validateState&nbsp;=&nbsp;!errors&nbsp;?&nbsp;&#39;success&#39;&nbsp;:&nbsp;&#39;error&#39;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validateMessage&nbsp;=&nbsp;errors&nbsp;?&nbsp;errors[0].message&nbsp;:&nbsp;&#39;&#39;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;callback(this.validateMessage); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;onFieldBlur()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validate(&#39;blur&#39;); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;onFieldChange()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validate(&#39;change&#39;); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">在 FormItem 的 `validate()` 方法中,最终做了两件事:</span></p><p><span style="text-wrap: nowrap;">1.&nbsp; 设置了当前的校验状态 `validateState` 和校验不通过提示信息 `validateMessage`(通过值为空);</span><br/></p><p><span style="text-wrap: nowrap;">2.&nbsp; 将 validateMessage 通过回调 callback 传递给调用者,这里的调用者是 onFieldBlur 和 onFieldChange,它们只传入了第一个参数 `trigger`,callback 并未传入,因此也不会触发回调,而</span></p><p><span style="text-wrap: nowrap;">这个回调主要是给 Form 用的,因为 Form 中可以通过提交按钮一次性校验所有的 FormItem(后文会介绍)这里只是表单组件触发事件时,对当前 FormItem 做校验。</span></p><p><span style="text-wrap: nowrap;">除了校验,还可以对当前数据进行重置。重置是指将表单组件的数据还原到最初绑定的值,而不是清空,因此需要预先缓存一份初始值。同时我们将校验信息也显示在模板中,并加一些样式。相</span><br/></p><p><span style="text-wrap: nowrap;">关代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;form-item.vue,部分代码省略&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;label&nbsp;v-if=&quot;label&quot;&nbsp;:class=&quot;{&nbsp;&#39;i-form-item-label-required&#39;:&nbsp;isRequired&nbsp;}&quot;&gt;{{&nbsp;label&nbsp;}}&lt;/label&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;slot&gt;&lt;/slot&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;div&nbsp;v-if=&quot;validateState&nbsp;===&nbsp;&#39;error&#39;&quot;&nbsp;class=&quot;i-form-item-message&quot;&gt;{{&nbsp;validateMessage&nbsp;}}&lt;/div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/div&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;props:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;label:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default:&nbsp;&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;prop:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;String &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;isRequired:&nbsp;false,&nbsp;&nbsp;//&nbsp;是否为必填 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validateState:&nbsp;&#39;&#39;,&nbsp;&nbsp;//&nbsp;校验状态 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validateMessage:&nbsp;&#39;&#39;,&nbsp;&nbsp;//&nbsp;校验不通过时的提示信息 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;如果没有传入&nbsp;prop,则无需校验,也就无需缓存 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(this.prop)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch(&#39;iForm&#39;,&nbsp;&#39;on-form-item-add&#39;,&nbsp;this); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;设置初始值,以便在重置时恢复默认值 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.initialValue&nbsp;=&nbsp;this.fieldValue; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.setRules(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setRules&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;rules&nbsp;=&nbsp;this.getRules(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(rules.length)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rules.every((rule)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;如果当前校验规则中有必填项,则标记出来 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.isRequired&nbsp;=&nbsp;rule.required; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-blur&#39;,&nbsp;this.onFieldBlur); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-form-change&#39;,&nbsp;this.onFieldChange); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;从&nbsp;Form&nbsp;的&nbsp;rules&nbsp;属性中,获取当前&nbsp;FormItem&nbsp;的校验规则 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;getRules&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;formRules&nbsp;=&nbsp;this.form.rules; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;formRules&nbsp;=&nbsp;formRules&nbsp;?&nbsp;formRules[this.prop]&nbsp;:&nbsp;[]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;[].concat(formRules&nbsp;||&nbsp;[]); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;重置数据 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;resetField&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validateState&nbsp;=&nbsp;&#39;&#39;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.validateMessage&nbsp;=&nbsp;&#39;&#39;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.form.model[this.prop]&nbsp;=&nbsp;this.initialValue; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt; &lt;style&gt; &nbsp;&nbsp;.i-form-item-label-required:before&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;content:&nbsp;&#39;*&#39;; &nbsp;&nbsp;&nbsp;&nbsp;color:&nbsp;red; &nbsp;&nbsp;} &nbsp;&nbsp;.i-form-item-message&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;color:&nbsp;red; &nbsp;&nbsp;} &lt;/style&gt;</pre><p><span style="text-wrap: nowrap;">至此,FormItem 代码已经完成,不过它只具有单独校验的功能,也就是说,只能对自己的一个表单组件验证,不能对一个表单域里的所有组件一次性全部校验。而实现全部校验和全部重置的功</span></p><p><span style="text-wrap: nowrap;">能,要在 Form 中完成。</span></p><p><span style="text-wrap: nowrap;">上文已经介绍到,在 `Form` 组件中,预先缓存了全部的 FormItem 实例,自然也能在 Form 中调用它们。通过点击提交按钮全部校验,或点击重置按钮全部重置数据,只需要在 Form 中,逐一</span><br/></p><p><span style="text-wrap: nowrap;">调用缓存的 FormItem 实例中的 `validate` 或 `resetField` 方法。相关代码如下:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;form.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fields:&nbsp;[] &nbsp;&nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;}, &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;公开方法:全部重置数据 &nbsp;&nbsp;&nbsp;&nbsp;resetFields()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.fields.forEach(field&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;field.resetField(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;公开方法:全部校验数据,支持&nbsp;Promise &nbsp;&nbsp;&nbsp;&nbsp;validate(callback)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;Promise(resolve&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;valid&nbsp;=&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;count&nbsp;=&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.fields.forEach(field&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;field.validate(&#39;&#39;,&nbsp;errors&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(errors)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;valid&nbsp;=&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(++count&nbsp;===&nbsp;this.fields.length)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;全部完成 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;resolve(valid); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(typeof&nbsp;callback&nbsp;===&nbsp;&#39;function&#39;)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;callback(valid); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}, }</pre><p><span style="text-wrap: nowrap;">虽然说 Vue.js 的 API 只来自 prop、event、slot 这三个部分,但一些场景下,需要通过 `ref` 来访问这个组件,调用它的一些内置方法,比如上面的 `validate` 和 `resetFields` 方法,就需要使</span></p><p><span style="text-wrap: nowrap;">用者来主动调用。</span></p><p><span style="text-wrap: nowrap;">resetFields 很简单,就是通过循环逐一调用 FormItem 的 resetField 方法来重置数据。validate 稍显复杂,它支持两种使用方法,一种是普通的回调,比如:</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form&nbsp;ref=&quot;form&quot;&gt;&lt;/i-form&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;button&nbsp;@click=&quot;handleSubmit&quot;&gt;提交&lt;/button&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleSubmit&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$refs.form.validate((valid)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(valid)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;提交成功&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;表单校验失败&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">同时也支持 Promise,例如:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">handleSubmit&nbsp;()&nbsp;{ &nbsp;&nbsp;const&nbsp;validate&nbsp;=&nbsp;this.$refs.form.validate(); &nbsp;&nbsp;validate.then((valid)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(valid)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;提交成功&#39;); &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;表单校验失败&#39;); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}) }</pre><p><span style="text-wrap: nowrap;">在 Form 组件定义的 Promise 中,只调用了 resolve(valid),没有调用 reject(),因此不能直接使用 `.catch()` ,不过聪明的你稍作修改,肯定能够支持到!</span></p><p><span style="text-wrap: nowrap;">完整的用例如下:</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;h3&gt;具有数据校验功能的表单组件——Form&lt;/h3&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form&nbsp;ref=&quot;form&quot;&nbsp;:model=&quot;formValidate&quot;&nbsp;:rules=&quot;ruleValidate&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form-item&nbsp;label=&quot;用户名&quot;&nbsp;prop=&quot;name&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;formValidate.name&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-form-item&nbsp;label=&quot;邮箱&quot;&nbsp;prop=&quot;mail&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;i-input&nbsp;v-model=&quot;formValidate.mail&quot;&gt;&lt;/i-input&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form-item&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/i-form&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;button&nbsp;@click=&quot;handleSubmit&quot;&gt;提交&lt;/button&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;button&nbsp;@click=&quot;handleReset&quot;&gt;重置&lt;/button&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;iForm&nbsp;from&nbsp;&#39;../components/form/form.vue&#39;; &nbsp;&nbsp;import&nbsp;iFormItem&nbsp;from&nbsp;&#39;../components/form/form-item.vue&#39;; &nbsp;&nbsp;import&nbsp;iInput&nbsp;from&nbsp;&#39;../components/input/input.vue&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;components:&nbsp;{&nbsp;iForm,&nbsp;iFormItem,&nbsp;iInput&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;data&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;formValidate:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;&#39;, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mail:&nbsp;&#39;&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ruleValidate:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;required:&nbsp;true,&nbsp;message:&nbsp;&#39;用户名不能为空&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mail:&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;required:&nbsp;true,&nbsp;message:&nbsp;&#39;邮箱不能为空&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;type:&nbsp;&#39;email&#39;,&nbsp;message:&nbsp;&#39;邮箱格式不正确&#39;,&nbsp;trigger:&nbsp;&#39;blur&#39;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleSubmit&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$refs.form.validate((valid)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(valid)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;提交成功&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(&#39;表单校验失败&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleReset&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$refs.form.resetFields(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">项目基于 Vue CLI 3 构建,下载安装依赖后,通过 npm run serve 可访问。</span></p>

Vue间组件通信之派发与广播

<p><span style="text-wrap: nowrap;"><br/></span></p><p><strong><span style="text-wrap: nowrap;">组件的通信 :派发与广播——自行实现 dispatch 和 broadcast 方法</span></strong></p><p><span style="text-wrap: nowrap;">上一讲的 provide / inject API 主要解决了跨级组件间的通信问题,不过它的使用场景,主要是子组件获取上级组件的状态,跨级组件间建立了一种主动提供与依赖注入的关系。然后有两种场景</span></p><p><span style="text-wrap: nowrap;">它不能很好的解决:</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;父组件向子组件(支持跨级)传递数据;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;子组件向父组件(支持跨级)传递数据。</span></p><p><span style="text-wrap: nowrap;">这种父子(含跨级)传递数据的通信方式,Vue.js 并没有提供原生的 API 来支持,而是推荐使用大型数据状态管理工具 Vuex,而我们之前已经介绍过 Vuex 的场景与在独立组件(或库)中使用</span><br/></p><p><span style="text-wrap: nowrap;">的限制。本小节则介绍一种在父子组件间通信的方法 `dispatch` 和 `broadcast`。</span></p><p><strong><span style="text-wrap: nowrap;">$on 与 $emit</span></strong><br/></p><p><span style="text-wrap: nowrap;">如果您使用过较早的 Vue.js 1.x 版本,肯定对 _$dispatch_ 和 _$broadcast_ 这两个内置的方法很熟悉,不过它们都在 Vue.js 2.x 里废弃了。在正式介绍主角前,我们先看看 `$on` 与 `$emit` 这</span><br/></p><p><span style="text-wrap: nowrap;">两个 API,因为它们是本节内容的基础。</span></p><p><span style="text-wrap: nowrap;">`$emit` 会在**当前组件**实例上触发自定义事件,并传递一些参数给监听器的回调,一般来说,都是在父级调用这个组件时,使用 `@on` 的方式来监听自定义事件的,比如在子组件中触发事件:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;child.vue,部分代码省略 export&nbsp;default&nbsp;{ &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;handleEmitEvent&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$emit(&#39;test&#39;,&nbsp;&#39;Hello&nbsp;Vue.js&#39;); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">在父组件中监听由 _child.vue_ 触发的自定义事件 **test**:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;parent.vue,部分代码省略--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;child-component&nbsp;@test=&quot;handleEvent&quot;&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleEvent&nbsp;(text)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(text);&nbsp;&nbsp;//&nbsp;Hello&nbsp;Vue.js &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">这里看似是在父组件 _parent.vue_ 中绑定的自定义事件 **test** 的处理句柄,然而事件 test 并不是在父组件上触发的,而是在子组件 _child.vue_ 里触发的,只是通过 `v-on` 在父组件中监听。</span></p><p><span style="text-wrap: nowrap;">既然是子组件自己触发的,那它自己也可以监听到,这就要使用 `$on` 来监听实例上的事件,换言之,组件使用 `$emit` 在自己实例上触发事件,并用 `$on` 监听它。</span></p><p><span style="text-wrap: nowrap;">听起来这种神(sāo)操作有点多此一举,我们不妨先来看个示例:</span><br/></p><p><span style="text-wrap: nowrap;">(也可通过在线链接 [https://run.iviewui.com/ggsomfHM](https://run.iviewui.com/ggsomfHM) 直接运行该示例)</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;template&gt; &nbsp;&nbsp;&lt;div&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;button&nbsp;@click=&quot;handleEmitEvent&quot;&gt;触发自定义事件&lt;/button&gt; &nbsp;&nbsp;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleEmitEvent&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;在当前组件上触发自定义事件&nbsp;test,并传值 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$emit(&#39;test&#39;,&nbsp;&#39;Hello&nbsp;Vue.js&#39;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;监听自定义事件&nbsp;test &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;test&#39;,&nbsp;(text)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(text); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">`$on` 监听了自己触发的自定义事件 test,因为有时不确定何时会触发事件,一般会在 `mounted` 或 `created` 钩子中来监听。</span></p><p><span style="text-wrap: nowrap;">仅上面的示例,的确是多此一举的,因为大可在 handleEmitEvent 里直接写 window.alert(text),没必要绕一圈。</span></p><p><span style="text-wrap: nowrap;">之所以多此一举,是因为 handleEmitEvent 是当前组件内的 `&lt;button&gt;` 调用的,如果这个方法不是它自己调用,而是其它组件调用的,那这个用法就大有可为了。</span></p><p><span style="text-wrap: nowrap;">了解了 `$on` 和 `$emit` 的用法后,我们再来看两个“过时的” API。</span></p><p><span style="text-wrap: nowrap;"><strong>Vue.js 1.x 的 $dispatch 与 $broadcast</strong></span></p><p><span style="text-wrap: nowrap;">虽然 Vue.js 1.x 已经成为过去时,但为了充分理解本节通信方法的使用场景,还是有必要来了解一点它的历史。</span></p><p><span style="text-wrap: nowrap;">在 Vue.js 1.x 中,提供了两个方法:`$dispatch` 和 `$broadcast` ,前者用于向上级派发事件,只要是它的父级(一级或多级以上),都可以在组件内通过 `$on` (或 events,2.x 已废弃)监听</span></p><p><span style="text-wrap: nowrap;">到,后者相反,是由上级向下级广播事件的。</span></p><p><span style="text-wrap: nowrap;">来看一个简单的示例:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;注意:该示例为&nbsp;Vue.js&nbsp;1.x&nbsp;版本&nbsp;--&gt; &lt;!--&nbsp;子组件&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;button&nbsp;@click=&quot;handleDispatch&quot;&gt;派发事件&lt;/button&gt; &lt;/template&gt; &lt;script&gt; export&nbsp;default&nbsp;{ &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;handleDispatch&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$dispatch(&#39;test&#39;,&nbsp;&#39;Hello,&nbsp;Vue.js&#39;); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} } &lt;/script&gt; &lt;!--&nbsp;父组件,部分代码省略&nbsp;--&gt; &lt;template&gt; &nbsp;&nbsp;&lt;child-component&gt;&lt;/child-component&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;mounted&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;test&#39;,&nbsp;(text)&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(text);&nbsp;&nbsp;//&nbsp;Hello,&nbsp;Vue.js &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt;</pre><p><span style="text-wrap: nowrap;">$broadcast 类似,只不过方向相反。这两种方法一旦发出事件后,任何组件都是可以接收到的,就近原则,而且会在第一次接收到后停止冒泡,除非返回 true。</span></p><p><span style="text-wrap: nowrap;">这两个方法虽然看起来很好用,但是在 Vue.js 2.x 中都废弃了,官方给出的解释是:</span><br/></p><p><span style="text-wrap: nowrap;">因为基于组件树结构的事件流方式有时让人难以理解,并且在组件结构扩展的过程中会变得越来越脆弱。</span><br/></p><p><span style="text-wrap: nowrap;">虽然在业务开发中,它没有 Vuex 这样专门管理状态的插件清晰好用,但对独立组件(库)的开发,绝对是福音。因为独立组件一般层级并不会很复杂,并且剥离了业务,不会变的难以维护。</span><br/></p><p><span style="text-wrap: nowrap;">知道了 _$dispatch_ 和 _$broadcast_ 的前世今生,接下来我们就在 Vue.js 2.x 中自行实现这两个方法。</span><br/></p><p><span style="text-wrap: nowrap;"><strong>自行实现 dispatch 和 broadcast 方法</strong></span><br/></p><p><span style="text-wrap: nowrap;">自行实现的 dispatch 和 broadcast 方法,不能保证跟 Vue.js 1.x 的 _$dispatch_ 和 _$broadcast_ 具有完全相同的体验,但基本功能是一样的,都是解决父子组件(含跨级)间的通信问题。</span><br/></p><p><span style="text-wrap: nowrap;">通过目前已知的信息,我们要实现的 dispatch 和 broadcast 方法,将具有以下功能:</span><br/></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;在子组件调用 dispatch 方法,向上级指定的组件实例(最近的)上触发自定义事件,并传递数据,且该上级组件已预先通过 `$on` 监听了这个事件;</span><br/></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;相反,在父组件调用 broadcast 方法,向下级指定的组件实例(最近的)上触发自定义事件,并传递数据,且该下级组件已预先通过 `$on` 监听了这个事件。</span></p><p><span style="text-wrap: nowrap;">实现这对方法的关键点在于,如何正确地向上或向下找到对应的组件实例,并在它上面触发方法。在设计一个新功能(features)时,可以先确定这个功能的 API 是什么,也就是说方法名、参</span><br/></p><p><span style="text-wrap: nowrap;">数、使用样例,确定好 API,再来写具体的代码。</span></p><p><span style="text-wrap: nowrap;">因为 Vue.js 内置的方法,才是以 `$` 开头的,比如 `$nextTick`、`$emit` 等,为了避免不必要的冲突并遵循规范,这里的 dispatch 和 broadcast 方法名前不加 `$`。并且该方法可能在很多组件</span><br/></p><p><span style="text-wrap: nowrap;">中都会使用,复用起见,我们封装在混合(mixins)里。那它的使用样例可能是这样的:</span></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">//&nbsp;部分代码省略 import&nbsp;Emitter&nbsp;from&nbsp;&#39;../mixins/emitter.js&#39; export&nbsp;default&nbsp;{ &nbsp;&nbsp;mixins:&nbsp;[&nbsp;Emitter&nbsp;], &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;handleDispatch&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.dispatch();&nbsp;&nbsp;//&nbsp;① &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;handleBroadcast&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.broadcast();&nbsp;&nbsp;//&nbsp;② &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">上例中行 ① 和行 ② 的两个方法就是在导入的混合 **emitter.js** 中定义的,这个稍后我们再讲,先来分析这两个方法应该传入什么参数。一般来说,为了跟 Vue.js 1.x 的方法一致,第一个参数</span></p><p><span style="text-wrap: nowrap;">应当是自定义事件名,比如 “test”,第二个参数是传递的数据,比如 “Hello, Vue.js”,但在这里,有什么问题呢?只通过这两个参数,我们没办法知道要在哪个组件上触发事件,因为自行实</span></p><p><span style="text-wrap: nowrap;">现的这对方法,与 Vue.js 1.x 的原生方法机理上是有区别的。上文说到,实现这对方法的关键点在于准确地**找到组件实例**。那在寻找组件实例上,我们的“惯用伎俩”就是通过遍历来匹配组</span></p><p><span style="text-wrap: nowrap;">件的 `name` 选项,在独立组件(库)里,每个组件的 `name` 值应当是唯一的,name 主要用于递归组件,在后面小节会单独介绍。</span></p><p><span style="text-wrap: nowrap;">先来看下 **emitter.js** 的代码:</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">function&nbsp;broadcast(componentName,&nbsp;eventName,&nbsp;params)&nbsp;{ &nbsp;&nbsp;this.$children.forEach(child&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;name&nbsp;=&nbsp;child.$options.name; &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(name&nbsp;===&nbsp;componentName)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;child.$emit.apply(child,&nbsp;[eventName].concat(params)); &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;broadcast.apply(child,&nbsp;[componentName,&nbsp;eventName].concat([params])); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}); } export&nbsp;default&nbsp;{ &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;dispatch(componentName,&nbsp;eventName,&nbsp;params)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;parent&nbsp;=&nbsp;this.$parent&nbsp;||&nbsp;this.$root; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;name&nbsp;=&nbsp;parent.$options.name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(parent&nbsp;&amp;&amp;&nbsp;(!name&nbsp;||&nbsp;name&nbsp;!==&nbsp;componentName))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent&nbsp;=&nbsp;parent.$parent; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(parent)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name&nbsp;=&nbsp;parent.$options.name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(parent)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent.$emit.apply(parent,&nbsp;[eventName].concat(params)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;broadcast(componentName,&nbsp;eventName,&nbsp;params)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;broadcast.call(this,&nbsp;componentName,&nbsp;eventName,&nbsp;params); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} };</pre><p><span style="text-wrap: nowrap;">因为是用作 mixins 导入,所以在 methods 里定义的 dispatch 和 broadcast 方法会被混合到组件里,自然就可以用 `this.dispatch` 和 `this.broadcast` 来使用。</span></p><p><span style="text-wrap: nowrap;">这两个方法都接收了三个参数,第一个是组件的 `name` 值,用于向上或向下递归遍历来寻找对应的组件,第二个和第三个就是上文分析的自定义事件名称和要传递的数据。</span><br/></p><p><span style="text-wrap: nowrap;">可以看到,在 dispatch 里,通过 _while_ 语句,不断向上遍历更新当前组件(即上下文为当前调用该方法的组件)的父组件实例(变量 parent 即为父组件实例),直到匹配到定义的</span><br/></p><p><span style="text-wrap: nowrap;">&nbsp;`componentName` 与某个上级组件的 `name` 选项一致时,结束循环,并在找到的组件实例上,调用 `$emit` 方法来触发自定义事件 `eventName`。broadcast 方法与之类似,只不过是向下</span></p><p><span style="text-wrap: nowrap;">遍历寻找。</span></p><p><span style="text-wrap: nowrap;">来看一下具体的使用方法。有 **A.vue** 和 **B.vue** 两个组件,其中 B 是 A 的子组件,中间可能跨多级,在 A 中向 B 通信:</span><br/></p><p><span style="text-wrap: nowrap;"></span></p><pre class="brush:js;toolbar:false">&lt;!--&nbsp;A.vue&nbsp;--&gt; &lt;template&gt; &lt;button&nbsp;@click=&quot;handleClick&quot;&gt;触发事件&lt;/button&gt; &lt;/template&gt; &lt;script&gt; &nbsp;&nbsp;import&nbsp;Emitter&nbsp;from&nbsp;&#39;../mixins/emitter.js&#39;; &nbsp;&nbsp;export&nbsp;default&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;name:&nbsp;&#39;componentA&#39;, &nbsp;&nbsp;&nbsp;&nbsp;mixins:&nbsp;[&nbsp;Emitter&nbsp;], &nbsp;&nbsp;&nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleClick&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.broadcast(&#39;componentB&#39;,&nbsp;&#39;on-message&#39;,&nbsp;&#39;Hello&nbsp;Vue.js&#39;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} &lt;/script&gt; //&nbsp;B.vue export&nbsp;default&nbsp;{ &nbsp;&nbsp;name:&nbsp;&#39;componentB&#39;, &nbsp;&nbsp;created&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;this.$on(&#39;on-message&#39;,&nbsp;this.showMessage); &nbsp;&nbsp;}, &nbsp;&nbsp;methods:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;showMessage&nbsp;(text)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.alert(text); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }</pre><p><span style="text-wrap: nowrap;">同理,如果是 B 向 A 通信,在 B 中调用 dispatch 方法,在 A 中使用 $on 监听事件即可。</span></p><p><span style="text-wrap: nowrap;">以上就是自行实现的 dispatch 和 broadcast 方法,相比 Vue.js 1.x,有以下不同:</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;需要额外传入组件的 name 作为第一个参数;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;无冒泡机制;</span></p><p><span style="text-wrap: nowrap;">*&nbsp; &nbsp;第三个参数传递的数据,只能是一个(较多时可以传入一个对象),而 Vue.js 1.x 可以传入多个参数,当然,你对 emitter.js 稍作修改,也能支持传入多个参数,只是一般场景传入一个对象</span></p><p><span style="text-wrap: nowrap;">足以。</span></p><p><br/></p>

shopify应用开发,shopify二次开发,shopify中文开发教程

<h5 style="color:red;">系统学习shopify开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank">《Shopify应用实战开发》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230612/03b58362c0718203696abbd7c748a136.jpg" alt="Shopify应用实战开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>这本小册将领您进入 Shopify 平台,学习开发出Shopify应用程序。作为全球最受欢迎的电子商务平台之一,Shopify 提供了一个强大的基础架构,让开发者可以创建个性化、功能丰富的在线商店。本课程将专注于 Shopify 应用开发,为您提供全面的指导和实践机会,打造功能齐全的app,帮助商家实现收益增长,作为个人开发者从中赚取收益。</p> </div> <hr><h5 style="color:red;">系统学习shopify开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank">《Shopify应用实战开发》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230612/03b58362c0718203696abbd7c748a136.jpg" alt="Shopify应用实战开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>这本小册将领您进入 Shopify 平台,学习开发出Shopify应用程序。作为全球最受欢迎的电子商务平台之一,Shopify 提供了一个强大的基础架构,让开发者可以创建个性化、功能丰富的在线商店。本课程将专注于 Shopify 应用开发,为您提供全面的指导和实践机会,打造功能齐全的app,帮助商家实现收益增长,作为个人开发者从中赚取收益。</p> </div> <hr><h5 style="color:red;">系统学习shopify开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank">《Shopify应用实战开发》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/shopify_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230612/03b58362c0718203696abbd7c748a136.jpg" alt="Shopify应用实战开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>这本小册将领您进入 Shopify 平台,学习开发出Shopify应用程序。作为全球最受欢迎的电子商务平台之一,Shopify 提供了一个强大的基础架构,让开发者可以创建个性化、功能丰富的在线商店。本课程将专注于 Shopify 应用开发,为您提供全面的指导和实践机会,打造功能齐全的app,帮助商家实现收益增长,作为个人开发者从中赚取收益。</p> </div> <hr><p><span style="color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, sans-serif; text-wrap: wrap; background-color: rgb(255, 255, 255);">这门课程将带领您进入 Shopify 平台,学习开发出Shopify应用程序。作为全球最受欢迎的电子商务平台之一,Shopify 提供了一个强大的基础架构,让开发者可以创建个性化、功能丰富的在线商店。本课程将专注于 Shopify 应用开发,为您提供全面的指导和实践机会,打造功能齐全的app,帮助商家实现收益增长,作为个人开发者从中赚取收益。</span></p><p><span style="color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, sans-serif; text-wrap: wrap; background-color: rgb(255, 255, 255);">shopify是一个独立站平台,类似于国内的淘宝,京东。商家可以在shopify平台开启自己的小店,打造自己的电子商务外贸平台。<br/></span></p><p><span style="color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, sans-serif; text-wrap: wrap; background-color: rgb(255, 255, 255);">同时,为了方便商家打造自己独特的个性平台,shopify平台提供了二次开发功能。商家可以通过自己编程的方式,为自己的店铺添加功能,帮助平台增加销售。</span></p><p><span style="color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, sans-serif; text-wrap: wrap; background-color: rgb(255, 255, 255);">shopify二次开发包含两个方向:shopify的app二次开发和shopify的店铺模板美化二次开发。</span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">shopify是一款国外的平台,目前在国内关于技术方面的二次开发教程较少。因此,码小课平台为大家提供了专门的shopify二次开发教程。本教程以一本小册的形式,为大家介绍shopify二次开发一个app并将该app添加到自己的店铺的完整项目开发过程。同时,也可以将自己开发出来的app上传到shopify官方平台上上架销售,当其他商家安装了我们开发的shopify功能的app后,会给我们支付收益。我们可以在shopify平台上赠取收益。</span></span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">本小册是国内唯一一部真正深入到shopify功能二次开发的教程。包含了shopify二次开发的完整流程,填补了国内shopify二次开发中文教程资料稀少的问题。</span></span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">大家可以在码小课中学习该教程,本小册一共分为二十几章内容,从shopify创建店铺,到创建shopify项目代码,进行二次开发编写代码,最终将自己开发的app上线等完整功能。</span></span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">通过这个shopify中文教程学会shopify的二次开发后,无论是想自己在shopify官方开店,给自己的店铺增加功能,还是单纯的以个人开发者名义开发shopify的app上架到shopify应用市场进行销售,赚取收益,都可以从这本shopify应用实战开发小册中掌握到全部技能。</span></span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">最后,祝愿大家早日掌握shopify二次开发技能。</span></span></p><p><span style="color:#4d5259;font-family:Microsoft YaHei, sans-serif"><span style="background-color: rgb(255, 255, 255);">本小册链接地址如下,可以直接点击跳转学习:</span></span></p><p><a href="http://www.maxiaoke.com/manual/shopify_dev.html" target="_blank"><strong>shopify应用实战开发</strong></a><br/></p><p><br/></p>

Apache服务器优化之数据压缩

<h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238);">一、数据压缩介绍</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">数据从服务器传输到客户端,需要传输时间,文件越大传输时间就越长,为了减少传输时间,我们一般把数据压缩后在传给客户端。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">apache支持两种压缩:deflate、gzip</p><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background: transparent; transition: all 0.3s linear 0s; outline: none !important;"></a>mod_gzip 和mod_deflate比较</h4><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">首先一个区别是安装它们的Apache Web服务器版本的差异。Apache 1.x系列没有内建网页压缩技术,所以才去用额外的第三方mod_gzip 模块来执行压缩。而Apache 2.x官方在开发的时候,就把网页压缩考虑进去,内建了mod_deflate 这个模块,用以取代mod_gzip。虽然两者都是使用的Gzip压缩算法,它们的运作原理是类似的。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">第二个区别是压缩质量。mod_deflate 压缩速度略快而mod_gzip 的压缩比略高。一般默认情况下,mod_gzip 会比mod_deflate 多出4%~6%的压缩量。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">那么,为什么使用mod_deflate?第三个区别是对服务器资源的占用。 一般来说mod_gzip 对服务器CPU的占用要高一些。mod_deflate 是专门为确保服务器的性能而使用的一个压缩模块,mod_deflate 需要较少的资源来压缩文件。这意味着在高流量的服务器,使用mod_deflate 可能会比mod_gzip 加载速度更快。</p><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background: transparent; transition: all 0.3s linear 0s; outline: none !important;"></a><strong style="box-sizing: border-box;">应用场景:数据压缩传输</strong></h4><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background: transparent; transition: all 0.3s linear 0s; outline: none !important;"></a><strong style="box-sizing: border-box;">优化目的:提升用户访问页面加载速度,节约带宽</strong></h4><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238);"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background: transparent; transition: all 0.3s linear 0s; outline: none !important;"></a>二、数据压缩实现</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">1)开启模块</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">LoadModule deflate_module modules/mod_deflate.so</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">2)调用模块</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">DeflateCompressionLevel 4</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript application/x-httpd-php</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">AddOutputFilter DEFLATE js css</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">BrowserMatch \bMSIE\s[1-6] dont-vary</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">SetEnvIfNoCase Request_URI .(?:pdf|doc)$ no-gzip dont-vary</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">&lt;IfModule&nbsp;deflate_module&gt; #&nbsp;压缩等级&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1-9,数字越大压缩的越好,也越占用CPU时间 DeflateCompressionLevel&nbsp;4 #&nbsp;压缩类型&nbsp;html、xml、php、css、js AddOutputFilterByType&nbsp;DEFLATE&nbsp;text/html&nbsp;text/plain&nbsp;text/xml&nbsp;application/x-javascript&nbsp;application/x-httpd-php AddOutputFilter&nbsp;DEFLATE&nbsp;js&nbsp;css #浏览器匹配&nbsp;IE1-6的不压缩 BrowserMatch&nbsp;\bMSIE\s[1-6]&nbsp;dont-vary #设置不压缩的文件,注意图片本身就是压缩过的,所以不需要再压缩 SetEnvIfNoCase&nbsp;Request_URI&nbsp;.(?:gif|jpe?g|png)$&nbsp;no-gzip&nbsp;dont-vary SetEnvIfNoCase&nbsp;Request_URI&nbsp;.(?:exe|t?gz|zip|bz2|sit|rar)$&nbsp;no-gzip&nbsp;dont-vary SetEnvIfNoCase&nbsp;Request_URI&nbsp;.(?:pdf|doc)$&nbsp;no-gzip&nbsp;dont-vary &lt;/IfModule&gt;</pre><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238);"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background: transparent; transition: all 0.3s linear 0s; outline: none !important;"></a>三、测试</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">1)生成HTML数据页面</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">for&nbsp;i&nbsp;in&nbsp;`seq&nbsp;1&nbsp;20`;do&nbsp;&nbsp;&nbsp;&nbsp;cat&nbsp;/etc/passwd&nbsp;&gt;&gt;&nbsp;/usr/local/apache/htdocs/test_deflate.htmldone</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">2)未启用压缩前通过浏览器访问该页面,通过开发者工具查看页面大小</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><img src="https://www.maxiaoke.com/uploads/images/20231230/96989d3e0f9fc03d9cb8f7566788784b.png" alt="" width="1145" height="656"/></p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;">3)启用压缩再次通过浏览器访问该页面,通过开发者工具查看页面大小,如果明显变小了则说明压缩成功。也可以从响应头中看出多了压缩字段。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><img src="https://www.maxiaoke.com/uploads/images/20231230/a43bc0eb502efe4f293d709c893b8c3d.png" alt="" width="1151" height="502"/></p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><img src="https://www.maxiaoke.com/uploads/images/20231230/a8697fe774807c14a91ef3d4c9fc3611.png" alt="" width="1136" height="764"/></p><p>上</p><p><br/></p>

Apache服务器优化之客户端缓存详解

<h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;">一、静态缓存介绍</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">用户每次访问网站都会将页面中的所有元素都请求一遍,全部下载后通过浏览器渲染,展示到浏览器中。但是,网站中的某些元素我们一般都是固定不变的,比如logo,框架文件等元。,用户每次访问都需要加载这些元素。这样做好处是保证了数据的新鲜,可是这些数据不是常变化的,很久才变化一次。每次都请求、下载浪费了用户时间和公司带宽。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">所以我们通过静态缓存的方式,将这些不常变化的数据缓存到用户本地磁盘,用户以后再访问这些请求,直接从本地磁盘打开加载,这样的好处是加载速度快,且节约公司带宽及成本。</p><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a><strong style="box-sizing: border-box;">应用场景:数据缓存</strong></h4><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a><strong style="box-sizing: border-box;">优化目的:提升用户访问页面加载速度,节约带宽</strong></h4><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>二、静态缓存实现</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">1)修改apache主配置文件,加载缓存模块</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">LoadModule expires_module modules/mod_expires.so</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">2)针对虚拟主机或者目录设置缓存策略</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">&lt;IfModule&nbsp;expires_module&gt; &nbsp;&nbsp;&nbsp;&nbsp;#开启缓存 &nbsp;&nbsp;&nbsp;&nbsp;ExpiresActive&nbsp;on &nbsp;&nbsp;&nbsp;&nbsp;#针对不同类型元素设置缓存时间 &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;image/gif&nbsp;&nbsp;&quot;access&nbsp;plus&nbsp;1&nbsp;days&quot; &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;image/jpeg&nbsp;&quot;access&nbsp;plus&nbsp;24&nbsp;hours&quot; &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;image/png&nbsp;&quot;access&nbsp;plus&nbsp;24&nbsp;hours&quot; &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;text/css&nbsp;&quot;now&nbsp;plus&nbsp;2&nbsp;hour&quot; &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;application/x-javascript&nbsp;&quot;now&nbsp;plus&nbsp;2&nbsp;hours&quot; &nbsp;&nbsp;&nbsp;&nbsp;ExpiresByType&nbsp;application/x-shockwave-flash&nbsp;&quot;now&nbsp;plus&nbsp;2&nbsp;hours” &nbsp;&nbsp;&nbsp;&nbsp;#其他数据不缓存 &nbsp;&nbsp;&nbsp;&nbsp;ExpiresDefault&nbsp;&quot;now&nbsp;plus&nbsp;0&nbsp;min&quot; &lt;/IfModule&gt; 缓存起始点 access&nbsp;&nbsp;&nbsp;从当前访问时间开始 now&nbsp;(equivalent&nbsp;to&nbsp;&#39;access&#39;)&nbsp;&nbsp;相当于access modification&nbsp;&nbsp;&nbsp;从修改时间算起 缓存时间单位 years months weeks days hours minutes seconds</pre><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>三、验证测试</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">缓存没有生效前</strong><br/><img src="https://www.maxiaoke.com/uploads/images/20231230/56b04d57f667a061ebea1ef833bc38b6.png" alt="" width="919" height="559"/></p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">缓存生效后测试</strong><br/><img src="https://www.maxiaoke.com/uploads/images/20231230/3892f40e922975685fc76138fb5cdb1c.png" alt="" width="920" height="775"/><br/>响应头中加载了缓存字段</p><p style="box-sizing: border-box; margin-top: 0px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap; margin-bottom: 0px !important;">Cache-control 和 Expires,并且缓存的时间和我们预设的一致,成功啦。</p><p><br/></p>

shell脚本编程实例之KFC餐厅点餐程序

<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><strong style="box-sizing: border-box;">案例需求</strong><br/>写一个程序,模拟KFC点餐系统,要求有以下功能:</p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em;" class=" list-paddingleft-2"><li><p>1、点餐功能</p></li><li><p>2、结算功能</p></li><li><p>3、打印流水单</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><strong style="box-sizing: border-box;">案例步骤</strong></p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em;" class=" list-paddingleft-2"><li><p>1、交互点餐</p></li><li><p>2、结账收银</p></li><li><p>3、打印流水单给客户</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><strong style="box-sizing: border-box;">案例代码</strong></p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">#!/bin/bash #&nbsp; #Author:www.zutuanxue.com # #Release:&nbsp; #Description:&nbsp; #1)录入单价 HBB=19.8 JC=12.3 KL=9.9 #2)定义输出 cat&nbsp;&lt;&lt;EOF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;welcome&nbsp;to&nbsp;KFC 今天KFC提供菜品如下: &nbsp;&nbsp;&nbsp;&nbsp;1)汉堡 &nbsp;&nbsp;&nbsp;&nbsp;2)鸡翅 &nbsp;&nbsp;&nbsp;&nbsp;3)可乐 EOF echo&nbsp;-e&nbsp;&quot;\n请您输入希望购买菜品的数量,不需要输入0\n&quot; ###1.用户交互 #定义变量类型为整形 declare&nbsp;-i&nbsp;NUM_HBB declare&nbsp;-i&nbsp;NUM_JC declare&nbsp;-i&nbsp;NUM_KL read&nbsp;-p&nbsp;&quot;汉堡:&nbsp;&quot;&nbsp;NUM_HBB read&nbsp;-p&nbsp;&quot;鸡翅:&nbsp;&quot;&nbsp;NUM_JC read&nbsp;-p&nbsp;&quot;可乐:&nbsp;&quot;&nbsp;NUM_KL ###2.计算输出 HBB_price=`echo&nbsp;&quot;scale=2;$HBB*$NUM_HBB&quot;|bc` JC_price=`echo&nbsp;&quot;scale=2;$JC*$NUM_JC&quot;|bc` KL_price=`echo&nbsp;&quot;scale=2;$KL*$NUM_KL&quot;|bc` total_price=`echo&nbsp;&quot;scale=2;$HBB_price+$JC_price+$KL_price&quot;|bc` ###3.付款 echo&nbsp;-n&nbsp;&quot;合计:&nbsp;$total_price&nbsp;&quot; read&nbsp;-p&nbsp;&quot;请付款:&nbsp;&quot;&nbsp;USER_price ###4.打印小票 clear echo&nbsp;-e&nbsp;&quot;\t\tKFC结算单&quot; echo&nbsp;&quot;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~&quot; echo&nbsp;-e&nbsp;&quot;商品\t单价\t数量\t合计&quot; echo&nbsp;-e&nbsp;&quot;汉堡包\t$HBB\t$NUM_HBB\t$HBB_price&quot; echo&nbsp;-e&nbsp;&quot;鸡翅\t$JC\t$NUM_JC\t$JC_price&quot; echo&nbsp;-e&nbsp;&quot;可乐\t$KL\t$NUM_KL\t$KL_price&quot; echo&nbsp;-e&nbsp;&quot;\n\n&quot; echo&nbsp;&quot;总计:&nbsp;$total_price&quot; echo&nbsp;-e&nbsp;&quot;支付:$USER_price&quot; echo&nbsp;-e&nbsp;&quot;找零:&nbsp;`echo&nbsp;&quot;scale=2;$USER_price-$total_price&quot;|bc`&quot; echo&nbsp;&quot;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~&quot; echo&nbsp;-e&nbsp;&quot;地址:北京东大桥路33号KFC店\n联系电话:400-123-456\nwww.kfc.com&quot;</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px;"><strong style="box-sizing: border-box;">案例效果</strong></p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 0px !important;"><img src="https://www.maxiaoke.com/uploads/images/20231230/6d68b3f528b66d82c1e094d122cad552.gif" alt=""/></p><p><br/></p><p><br/></p>

shell脚本编程之shell运算详解

<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">计算机编程就是三大步:输入、运算、输出</strong></p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">那么计算机运算有哪些呢,计算机能做哪些运算呢?</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">我们来看看常见的计算机运算</strong></p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>一、赋值运算</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">赋值运算符 =</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;a=10&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name=&#39;baism&#39; &nbsp;重点:字符串必须用引号引起来</pre><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>二、算术运算[四则运算]</h2><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.1 运算符与命令</h3><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">四则运算符:</strong>&nbsp;+ -&nbsp;<em style="box-sizing: border-box;">\ 【加减乘除】<br/><strong style="box-sizing: border-box;">扩展:</strong>&nbsp;% *</em>&nbsp;【取余 开方】</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">运算命令:</strong></p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;" class=" list-paddingleft-2"><li><p>整形运算<br/>– expr<br/>– let<br/>– $(())<br/>– bc</p></li><li><p>浮点运算<br/>– bc</p></li></ul><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.2 整形运算</h3><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">expr 命令:只能做整数运算,格式比较古板,注意空格</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">[root@zutuanxue&nbsp;~]#&nbsp;expr&nbsp;1&nbsp;+&nbsp;1 2 [root@zutuanxue&nbsp;~]#&nbsp;expr&nbsp;5&nbsp;-&nbsp;2 3 [root@zutuanxue&nbsp;~]#&nbsp;expr&nbsp;5&nbsp;\*&nbsp;2&nbsp;&nbsp;#注意*出现应该转义,否则认为是通配符 10 [root@zutuanxue&nbsp;~]#&nbsp;expr&nbsp;5&nbsp;/&nbsp;2 2 [root@zutuanxue&nbsp;~]#&nbsp;expr&nbsp;5&nbsp;%&nbsp;2 1</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">let命令:只能做整数运算,且运算元素必须是变量,无法直接对整数做运算</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">[root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100+3;echo&nbsp;$a 103 root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100-3;echo&nbsp;$a 97 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100/3;echo&nbsp;$a 33 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100*3;echo&nbsp;$a 300 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100%3;echo&nbsp;$a 1 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a=100**3;echo&nbsp;$a 1000000 [root@zutuanxue&nbsp;~]#&nbsp;a=100 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a++;echo&nbsp;$a 101 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a--;echo&nbsp;$a 100 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a-=3;echo&nbsp;$a 97 [root@zutuanxue&nbsp;~]#&nbsp;let&nbsp;a+=5;echo&nbsp;$a 102</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">双小圆括号运算,在shell中(( ))也可以用来做数学运算</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">[root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100+3)) 103 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100-3))&nbsp; 97 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100%3)) 1 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100*3)) 300 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100/3)) 33 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;$((&nbsp;100**3))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#开方运算 1000000</pre><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.3 浮点运算</h3><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">浮点运算是采用的命令组合的方式来实现的 echo “scale=N;表达式”|bc</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">[root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;&quot;scale=2;3+100&quot;|bc 103 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;&quot;scale=2;100-3&quot;|bc 97 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;&quot;scale=2;100/3&quot;|bc 33.33 [root@zutuanxue&nbsp;~]#&nbsp;echo&nbsp;&quot;scale=2;100*3&quot;|bc 300</pre><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.4、练习案例</h3><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.4.1 实现一个四则运算计算器</h4><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">案例思考:</strong>&nbsp;计算器的功能: + - * \</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">实现步骤:</strong><br/>1、要求用户传输三个参数,num1 算术运算符 num2<br/>2、运算输出结果</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">实现代码</strong></p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">##03_calculator.sh #!/bin/bash #&nbsp; #Author:&nbsp;www.zutuanxue.com #Release:&nbsp; #Description:&nbsp;简单计算器 echo&nbsp;&quot;$1&nbsp;$2&nbsp;$3&quot;|bc</pre><h4 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.4; font-size: 1.25em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>2.4.2 内存使用率统计,要求打印内存使用率</h4><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">案例思考:</strong></p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;" class=" list-paddingleft-2"><li><p>物料1、内存总量 获得方式是什么 free top /proc/meminfo</p></li><li><p>物料2、内存使用量</p></li><li><p>物料3、内存使用率公式 使用量/总量*100%</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">实现步骤:</strong></p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;" class=" list-paddingleft-2"><li><p>1、获取内存总量</p></li><li><p>2、获取内存使用量</p></li><li><p>3、运算输出结果</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">实现代码</strong></p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">#job实现代码&nbsp;&nbsp;04_memory_use.sh #!/bin/bash #&nbsp; #Author:&nbsp;www.zutuanxue.com #Release:&nbsp; #Description:内存使用率计算脚本 #free #1、获得内存总量 memory_total=`free&nbsp;-m|grep&nbsp;-i&nbsp;&quot;mem&quot;|tr&nbsp;-s&nbsp;&quot;&nbsp;&quot;|cut&nbsp;-d&nbsp;&quot;&nbsp;&quot;&nbsp;-f2` #2、获得内存使用的量 memory_use=`free&nbsp;-m|grep&nbsp;-i&nbsp;&quot;mem&quot;|tr&nbsp;-s&nbsp;&quot;&nbsp;&quot;|cut&nbsp;-d&nbsp;&quot;&nbsp;&quot;&nbsp;-f3` #3、计算输出 #运算的时候是否需要小数点&nbsp;浮点运算,要考虑使用的命令&nbsp;(难点&nbsp;重点) #echo&nbsp;&quot;内存使用率:&nbsp;$((memory_use*100/memory_total))%&quot; #难点:浮点运算中,同优先级的情况下,大数除以小数&nbsp;尽可能保证精确 echo&nbsp;&quot;内存使用率:&nbsp;`echo&nbsp;&quot;scale=2;$memory_use*100/$memory_total&quot;|bc`%&quot;</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">实现效果</strong></p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">#运算结果[root@zutuanxue&nbsp;day2]#&nbsp;sh&nbsp;memory_use.sh&nbsp;Memory使用率:&nbsp;2.61%</pre><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>三、比较运算</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">计算机除了算术和赋值运算外,还有比较运算,比如说比较两个数的关系,比较两个字符串的关系【用户登录系统】等。接下来我们学习如何在shell中进行比较运算</p><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>3.1、整形比较运算</h3><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;运算符解释: &nbsp;精确比较 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-eq&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;等于&nbsp;equal &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-gt&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;大于 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-lt&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;小于 &nbsp;模糊比较 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-ge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;大于或等于 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-le&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;小于或等于 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-ne&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;不等于</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;"><strong style="box-sizing: border-box;">通过test命令比较两个整数关系</strong></p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">[root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-gt&nbsp;300;echo&nbsp;$? 1 [root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-ge&nbsp;300;echo&nbsp;$? 1 [root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-eq&nbsp;300;echo&nbsp;$? 1 [root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-le&nbsp;300;echo&nbsp;$? 0 [root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-lt&nbsp;300;echo&nbsp;$? 0 [root@zutuanxue&nbsp;~]#&nbsp;test&nbsp;100&nbsp;-ne&nbsp;300;echo&nbsp;$? 0 备注:linux命令test只能比较两个整数的关系,不会返回结果,需要通过$?才能看到结果</pre><h3 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 16px; font-weight: 300; line-height: 1.43; font-size: 1.5em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; color: rgb(77, 82, 89); text-wrap: wrap;"><br/><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a></h3>

go语言深入解析之go调用和汇编C

<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">只要不使用C的标准库函数,Go中是可以直接调用C和汇编语言的。其实道理很简单,Go的运行时库就是用C和汇编实现的,Go必须是能够调用到它们的。当然,会有一些额外的约束,这就是函数调用协议。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>Go中调用汇编</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">假设我们做一个汇编版本的加法函数。首先GOPATH的src下新建一个add目录,然后在该目录加入add.go的文件,内容如下:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">package&nbsp;add func&nbsp;Add(a,&nbsp;b&nbsp;uint64)&nbsp;uint64&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;a+b }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">这个函数将两个uint64的数字相加,并返回结果。我们写一个简单的函数调用它,内容如下:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">package&nbsp;main import&nbsp;( &nbsp;&nbsp;&quot;fmt&quot; &nbsp;&nbsp;&quot;add&quot; ) func&nbsp;main()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fmt.Println(add.Add(2,&nbsp;15)) }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">可以看到输出了结果为17。好的,接下来让我们删除Add函数的实现,只留下定义部分:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">package&nbsp;add func&nbsp;Add(a,&nbsp;b&nbsp;uint64)&nbsp;uint64</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">然后在add.go同一目录中建立一个add_amd64.s的文件(假设你使用的是64位系统),内容如下:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">TEXT&nbsp;&nbsp;&nbsp;&nbsp;·Add+0(SB),$0-24 MOVQ&nbsp;&nbsp;&nbsp;&nbsp;a+0(FP),BX MOVQ&nbsp;&nbsp;&nbsp;&nbsp;b+8(FP),BP ADDQ&nbsp;&nbsp;&nbsp;&nbsp;BP,BX MOVQ&nbsp;&nbsp;&nbsp;&nbsp;BX,res+16(FP) RET&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">虽然汇编是相当难理解的,但我相信读懂上面这段不会有困难。前两条MOVQ指令分别将第一个参数放到寄存器BX,第二个参数放到寄存器BP,然后ADDQ指令将两者相加后,最后的MOVQ和RET指令返回结果。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">现在,再次运行前面的main函数,它将使用自定义的汇编版本函数,可以看到成功的输出了结果17。从这个例子中可以看出Go是可以直接调用汇编实现的函数的。大多时候不必要你去写汇编,即使是研究Go的内部实现,能读懂汇编已经很足够了。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">也许你真的觉得在Go中写汇编很酷,但是不要忽视了这些忠告:</p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;" class=" list-paddingleft-2"><li><p>汇编很难编写,特别是很难写好。通常编译器会比你写出更快的代码。</p></li><li><p>汇编仅能运行在一个平台上。在这个例子中,代码仅能运行在 amd64 上。这个问题有一个解决方案是给 Go 对于 x86 和 不同版本的代码分别写一套代码,文件名相应的以_386.s和_arm.s结尾。</p></li><li><p>汇编让你和底层绑定在一起,而标准的 Go 不会。例如,slice 的长度当前是 32 位整数。但是也不是不可能为长整型。当发生这些变化时,这些代码就被破坏了。</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">当前Go编译器不能将汇编编译为函数的内联,但是对于小的Go函数是可以的。因此使用汇编可能意味着让你的程序更慢。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">有时需要汇编给你带来一些力量(不论是性能方面的原因,还是一些相当特殊的关于CPU的操作)。对于什么时候应该使用它,Go源码包括了若干相当好的例子(可以看看 crypto 和 math)。由于它非常容易实践,所以这绝对是个学习汇编的好途径。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>Go中调用C</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">接下来,我们继续尝试在Go中调用C,跟调用汇编的过程很类似。首先删掉前面的add_amd64.s文件,并确保add.go文件中只是给出了Add函数的声明部分:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">package&nbsp;add func&nbsp;Add(a,&nbsp;b&nbsp;uint64)&nbsp;uint64</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">然后在add.go同目录中,新建一个add.c文件,内容如下:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">#include&nbsp;&quot;runtime.h&quot; void&nbsp;·Add(uint64&nbsp;a,&nbsp;uint64&nbsp;b,&nbsp;uint64&nbsp;ret)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;ret&nbsp;=&nbsp;a&nbsp;+&nbsp;b; &nbsp;&nbsp;&nbsp;&nbsp;FLUSH(&amp;ret); }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">编译该包,运行前面的测试函数:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">go&nbsp;install&nbsp;add</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">会发现输出结果为17,说明Go中成功地调用到了C写的函数。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">要注意的是不管是C或是汇编实现的函数,其函数名都是以·开头的。还有,C文件中需要包含runtime.h头文件。这个原因在该文件中有说明:<br/>Go用了特殊寄存器来存放像全局的struct G和struct M。包含这个头文件可以让所有链接到Go的C文件都知道这一点,这样编译器可以避免使用这些特定的寄存器作其它用途。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">让我们仔细看一下这个C实现的函数。可以看到函数的返回值为空,而参数多了一个,第三个参数实际上被作为了返回值使用。其中FLUSH是在pkg/runtime/runtime.h中定义为USED(x),这个定义是Go的C编译器自带的primitive,作用是抑制编译器优化掉对*x的赋值的。如果你很好奇USED是怎样定义的,可以去$GOROOT/include/libc.h文件里去找找。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">被调函数中对参数ret的修改居然返回到了调用函数,这个看起来似乎不可理解,不过早期的C编译器确实是可以这么做的。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>函数调用时的内存布局</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">Go中使用的C编译器其实是plan9的C编译器,和我们平时理解的gcc等会有一些区别。我们将上面的add.c汇编一下:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">go&nbsp;tool&nbsp;6c&nbsp;-I&nbsp;$GOROOT/src/pkg/runtime&nbsp;-S&nbsp;add.c</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">生成的汇编代码大概是这个样子的:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">&quot;&quot;.Add&nbsp;t=1&nbsp;size=16&nbsp;value=0&nbsp;args=0x18&nbsp;locals=0 000000&nbsp;00000&nbsp;(add.c:3)&nbsp;&nbsp;&nbsp;&nbsp;TEXT&nbsp;&nbsp;&nbsp;&nbsp;&quot;&quot;.Add+0(SB),4,$0-24 000000&nbsp;00000&nbsp;(add.c:3)&nbsp;&nbsp;&nbsp;&nbsp;NOP&nbsp;&nbsp;&nbsp;&nbsp;, 000000&nbsp;00000&nbsp;(add.c:3)&nbsp;&nbsp;&nbsp;&nbsp;NOP&nbsp;&nbsp;&nbsp;&nbsp;, 000000&nbsp;00000&nbsp;(add.c:3)&nbsp;&nbsp;&nbsp;&nbsp;FUNCDATA&nbsp;&nbsp;&nbsp;&nbsp;$2,gcargs.0&lt;&gt;+0(SB) 000000&nbsp;00000&nbsp;(add.c:3)&nbsp;&nbsp;&nbsp;&nbsp;FUNCDATA&nbsp;&nbsp;&nbsp;&nbsp;$3,gclocals.1&lt;&gt;+0(SB) 000000&nbsp;00000&nbsp;(add.c:4)&nbsp;&nbsp;&nbsp;&nbsp;MOVQ&nbsp;&nbsp;&nbsp;&nbsp;a+8(FP),AX 0x0005&nbsp;00005&nbsp;(add.c:4)&nbsp;&nbsp;&nbsp;&nbsp;ADDQ&nbsp;&nbsp;&nbsp;&nbsp;b+16(FP),AX 0x000a&nbsp;00010&nbsp;(add.c:4)&nbsp;&nbsp;&nbsp;&nbsp;MOVQ&nbsp;&nbsp;&nbsp;&nbsp;AX,c+24(FP) 0x000f&nbsp;00015&nbsp;(add.c:5)&nbsp;&nbsp;&nbsp;&nbsp;RET&nbsp;&nbsp;&nbsp;&nbsp;, 000000&nbsp;48&nbsp;8b&nbsp;44&nbsp;24&nbsp;08&nbsp;48&nbsp;03&nbsp;44&nbsp;24&nbsp;10&nbsp;48&nbsp;89&nbsp;44&nbsp;24&nbsp;18&nbsp;c3&nbsp;&nbsp;H.D$.H.D$.H.D$..</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">这是Go使用的汇编代码,是一种类似plan9的汇编代码。类似a+8(FP)这种表示的含义是“变量名+偏移(寄存器)”。其中FP是帧寄存器,它是一个伪寄存器,实际上是内存位置的一个引用,其实就是BP(栈基址寄存器)上移一个机器字长位置的内存地址。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">函数调用之前,a+8(FP),b+16(FP)分别表示参数a和b,而参数3的位置被空着,在被调函数中,这个位置将用于存放返回值。此时的其内存布局如下所示:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">参数3参数2参数1&nbsp;&nbsp;&lt;-SP</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">进入被调函数之后,内存布局如下所示:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">参数3参数2参数1&nbsp;&nbsp;&lt;-FP保存PC&nbsp;&lt;-SP......</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">CALL指令会使得SP下移,SP位置的内存用于保存返回地址。帧寄存器FP此时位置在SP上面。在plan9汇编中,进入函数之后的前几条指令并没有出现<code style="box-sizing: border-box; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; font-size: 14px; color: rgb(232, 62, 140); overflow-wrap: break-word; padding: 3px; margin: 0px 4px 0px 5px; background: rgb(246, 246, 246); border-radius: 3px; border: 1px solid rgb(238, 238, 238);">push ebp; mov esp ebp</code>这种模式。plan9函数调用协议中采用的是caller-save的模式,也就是由调用者负责保存寄存器。注意这和传统的C是不同的。传统C中是callee-save的模式,被调函数要负责保存它想使用的寄存器,在函数退出时恢复这些寄存器。</p><p style="box-sizing: border-box; margin-top: 0px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap; margin-bottom: 0px !important;">需要注意的是参数和返回值都是有对齐的。这里是按Structrnd对齐的,Structrnd在源代码中义为sizeof(uintptr)。</p><p><br/></p>

go语言深入解析之nil类型的实现

<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">什么?nil是一种数据结构么?为什么会讲到它,没搞错吧?没搞错。不仅仅是Go语言中,每门语言中nil都是非常重要的,它代表的是空值的语义。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">在不同语言中,表示空这个概念都有细微不同。比如在scheme语言(一种lisp方言)中,nil是true的!而在ruby语言中,一切都是对象,连nil也是一个对象!在C中NULL跟0是等价的。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">按照Go语言规范,任何类型在未初始化时都对应一个零值:布尔类型是false,整型是0,字符串是””,而指针,函数,interface,slice,channel和map的零值都是nil。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>interface</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">一个interface在没有进行初始化时,对应的值是nil。也就是说<code style="box-sizing: border-box; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; font-size: 14px; color: rgb(232, 62, 140); overflow-wrap: break-word; padding: 3px; margin: 0px 4px 0px 5px; background: rgb(246, 246, 246); border-radius: 3px; border: 1px solid rgb(238, 238, 238);">var v interface{}</code>,</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">此时v就是一个nil。在底层存储上,它是一个空指针。与之不同的情况是,interface值为空。比如:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">var&nbsp;v&nbsp;*T var&nbsp;i&nbsp;interface{} i&nbsp;=&nbsp;v</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">此时i是一个interface,它的值是nil,但它自身不为nil。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">Go中的error其实就是一个实现了Error方法的接口:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">type&nbsp;error&nbsp;interface&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;Error()&nbsp;string }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">因此,我们可以自定义一个error:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">type&nbsp;Error&nbsp;struct&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;errCode&nbsp;uint8 } func&nbsp;(e&nbsp;*Error)&nbsp;Error()&nbsp;string&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;switch&nbsp;e.errCode&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case&nbsp;1: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;file&nbsp;not&nbsp;found&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case&nbsp;2: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;time&nbsp;out&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case&nbsp;3: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;permission&nbsp;denied&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;unknown&nbsp;error&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">如果我们这样使用它:</p><pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; font-variant-numeric: normal; font-variant-east-asian: normal; font-variant-alternates: normal; font-kerning: auto; font-optical-sizing: auto; font-feature-settings: normal; font-variation-settings: normal; font-variant-position: normal; font-stretch: normal; font-size: 13.6px; line-height: 1.6; font-family: &quot;YaHei Consolas Hybrid&quot;, Consolas, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Helvetica, monospace, monospace; margin-top: 0px; margin-bottom: 16px; overflow: auto; color: rgb(47, 111, 159); background-color: rgb(246, 246, 246); border: 1px solid rgb(238, 238, 238); padding: 10px; border-radius: 3px; overflow-wrap: break-word; text-wrap: wrap;">func&nbsp;checkError(err&nbsp;error)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;err&nbsp;!=&nbsp;nil&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;panic(err) &nbsp;&nbsp;&nbsp;&nbsp;} } var&nbsp;e&nbsp;*Error checkError(e)</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">e是nil的,但是当我们checkError时就会panic。请读者思考一下为什么?</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">总之,interface跟C语言的指针一样非常灵活,关于空的语义,也跟空指针一样容易困扰新手的,需要注意。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>string和slice</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">string的空值是””,它是不能跟nil比较的。即使是空的string,它的大小也是两个机器字长的。slice也类似,它的空值并不是一个空指针,而是结构体中的指针域为空,空的slice的大小也是三个机器字长的。</p><h2 style="box-sizing: border-box; margin-top: 0.3em; margin-bottom: 1em; font-weight: 300; line-height: 1.225; font-size: 1.75em; font-family: Raleway, 微軟正黑體, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; letter-spacing: 0.5px; position: relative; padding-bottom: 0.5em; border-bottom: 1px solid rgb(238, 238, 238); color: rgb(77, 82, 89); text-wrap: wrap;"><a class="reference-link" style="box-sizing: border-box; color: rgb(51, 202, 187); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; transition: all 0.3s linear 0s; outline: none !important;"></a>channel和map</h2><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">channel跟string或slice有些不同,它在栈上只是一个指针,实际的数据都是由指针所指向的堆上面。</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;">跟channel相关的操作有:初始化/读/写/关闭。channel未初始化值就是nil,未初始化的channel是不能使用的。下面是一些操作规则:</p><ul style="box-sizing: border-box; margin-bottom: 16px; padding: 0px 0px 0px 2em; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap;" class=" list-paddingleft-2"><li><p>读或者写一个nil的channel的操作会永远阻塞。</p></li><li><p>读一个关闭的channel会立刻返回一个channel元素类型的零值。</p></li><li><p>写一个关闭的channel会导致panic。</p></li></ul><p style="box-sizing: border-box; margin-top: 0px; color: rgb(77, 82, 89); font-family: &quot;Microsoft YaHei&quot;, Helvetica, &quot;Meiryo UI&quot;, &quot;Malgun Gothic&quot;, &quot;Segoe UI&quot;, &quot;Trebuchet MS&quot;, Monaco, monospace, Tahoma, STXihei, 华文细黑, STHeiti, &quot;Helvetica Neue&quot;, &quot;Droid Sans&quot;, &quot;wenquanyi micro hei&quot;, FreeSans, Arimo, Arial, SimSun, 宋体, Heiti, 黑体, sans-serif; text-wrap: wrap; margin-bottom: 0px !important;">map也是指针,实际数据在堆中,未初始化的值是nil。</p><p><br/></p>