Vue基础二之全局API、实例属性和全局配置,以及组件进阶(mixins)的详细教程(案列实现,详细图解,附源码)

博客 动态
0 258
羽尘
羽尘 2022-04-08 20:57:42
悬赏:0 积分 收藏

Vue基础二之全局API、实例属性和全局配置,以及组件进阶(mixins)的详细教程(案列实现,详细图解,附源码)

Vue基础二之全局API、实例属性和全局配置,以及组件进阶(mixins)的详细教程(案列实现,详细图解,附源码) 本篇文章主要是写Vue.directive()、Vue.use()等常用全局API的使用,vm.$props、vm.$options、vm.$slots等实例属性的使用,以及Vue全局配置、组件的mixins、组件中渲染函数的使用。

前言

本篇随笔主要讲解Vue中的全局API、实例属性和全局配置,以及组件进阶的基础知识,作为自己对Vue框架基础语法知识的总结与笔记。

因内容有案例解读,代码实现,导致篇幅稍长,大约3分钟可以浏览完,如有帮助的话(请笔友耐心看完)

长话不说,直接进入正题......

 

案例实现模版:

以下案例均是基于此模版实现的(以第一个案例为例)

 1 <!DOCTYPE html> 2 <html> 3 <head> 4   <meta charset="UTF-8"> 5   <title>模版</title> 6   <script src="vue.js"></script> 7 </head> 8 <body> 9 10   <!-- 以下是第一个小案例 -->11   <div id="app">12     <input type="text" v-focus="true">13   </div>14   <script>15     Vue.directive('focus', {16       inserted (el, binding) {17         if (binding.value) {18           el.focus()19         }20       }21     })22     var vm = new Vue({ el: '#app' })23  </script>24 25 26 </body>27 </html>

一、全局API

全局API并不在构造器里,而是先声明全局变量或者直接在Vue上定义一些新功能,Vue内置了一些全局API。说的简单些就是,在构造器外部用Vue提供给我们的API函数来定义新的功能。

1.Vue.directive

用来注册自定义指令,对低级DOM元素进行访问,为DOM元素添加新的特性。

 案例:自定义注册指令v-focus。

1.1 实现步骤

  • 定义根标签div。
  • 控制input文本框是否自动获得焦点。

1.2 代码实现

 1  <div id="app"> 2     <input type="text" v-focus="true"> 3   </div> 4   <script> 5     Vue.directive('focus', { 6       inserted (el, binding) { 7         if (binding.value) { 8           el.focus() 9         }10       }11     })12     var vm = new Vue({ el: '#app' })13  </script>

1.3 效果展示

2.Vue.use

Vue.use主要用于在Vue中安装插件,通过插件可以为Vue添加全局功能。插件可以是一个对象或函数,如果是对象,必须提供install()方法,用来安装插件;如果是一个函数,则该函数将被当成install()方法。

2.1 实现步骤

  • 创建vm实例
  • 定义插件
  • 使用插件

2.2 代码实现

 1 <div id="app" v-my-directive></div> 2   <script> 3     // 定义一个MyPlugin(自定义插件)对象 4     let MyPlugin = {} 5     // 编写插件对象的install方法 6     MyPlugin.install = function (Vue, options) { 7       console.log(options) 8       // 在插件中为Vue添加自定义指令 9       Vue.directive('my-directive', {10         bind (el, binding) {11           // 为自定义指令v-my-directive绑定的DOM元素设置style样式12           el.style = 'width:100px;height:100px;background-color:#ccc;'13         }14       })15     }16     Vue.use(MyPlugin, { someOption: true })17     var vm = new Vue({18       el: '#app'19     })20     // var Vue = require('Vue')21     // var vueRouter = require('vue-router')22     // Vue.use(vueRouter)23  </script>

2.3 效果展示

PS:

Vue.js官方提供的一些插件(如vue-router)在检测到 Vue 是可访问的全局变量时,会自动调用 Vue.use()。但是在CommonJS等模块环境中,则始终需要Vue.use()显式调用。

3.Vue.extend

Vue.extend用于基于Vue构造器创建一个Vue子类,可以对Vue构造器进行扩展。它有一个options参数,表示包含组件选项的对象。

3.1 实现步骤

  • 页面结构
  • 创建子类Vue2

3.2 代码实现

 1   <div id="app1">app1: {{title}}</div> 2   <div id="app2">app2: {{title}}</div> 3   <script> 4     var Vue2 = Vue.extend({ 5       data () { 6         return { title: 'hello' } 7       } 8     }) 9     var vm1 = new Vue({ el: '#app1' })10     var vm2 = new Vue2({ el: '#app2' })11  </script>

3.3 效果展示

4.Vue.set

Vue的核心具有一套响应式系统,简单来说就是通过监听器监听数据层的数据变化,当数据改变后,通知视图也自动更新。

Vue.set用于向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。

4.1 实现步骤

  • 页面结构
  • 创建vm对象动态设置属性b

4.2 代码实现

 1  <div id="app"> 2     <div>{{a}}</div> 3     <div>{{obj.b}}</div> 4   </div> 5   <script> 6     var vm = new Vue({ 7       el: '#app', 8       data: { 9         a: '我是根级响应式属性a',10         obj: {}11       }12     })13     Vue.set(vm.obj, 'b', '我是Vue.set添加的响应式属性obj.b')14  </script>

4.3 效果展示

5.Vue.mixin

Vue.mixin用于全局注册一个混入,它将影响之后创建的每个Vue实例。该接口主要是提供给插件作者使用,在插件中向组件注入自定义的行为。该接口不推荐在应用代码中使用。

案例:Vue.mixin用于全局注册一个混入( Mixins ),实现插件功能。

5.1 实现步骤

  • myOption是一个自定义属性。
  • 使用Vue.mixin

5.2 代码实现

 1   <div id="app"></div> 2   <script> 3     Vue.mixin({ 4       created () { 5         var myOption = this.$options.myOption 6         if (myOption) { 7           console.log(myOption.toUpperCase()) 8         } 9       }10     })11     var vm = new Vue({12       myOption: 'hello vue!'13     })14  </script>

5.3 效果展示

二、实例属性

1.vm.$props

使用vm.$props属性可以接收上级组件向下传递的数据。

案例:通过$props实现手机信息搜索。

1.1 实现步骤

  • 定义唯一根标签div。
  • 定义父组件模板。
  • 定义子组件模板。
  • 注册父组件my-parent。
  • 注册子组件my-child。
  • 在子组件的data中定义手机的数据信息。
  • 在子组件的data中定义props用来接收name的值。
  • 如果获取到name值就查询手机信息,否则返回。
  • 通过forEach()方法对手机数据进行查询操作。

1.2 代码实现

 1 <div id="app"> 2     <!-- 父组件 --> 3     <my-parent></my-parent> 4   </div> 5  6   <!-- 父组件模板 --> 7   <template id="parent"> 8     <div> 9       <h3>手机信息搜索</h3>10       手机品牌:<input type="text" v-model="brand">11       <!-- 子组件 -->12       <my-child v-bind:name="brand"></my-child>13     </div>14   </template>15 16   <!-- 子组件模板 -->17   <template id="child">18     <ul>19       <li>手机品牌:{{show.brand}}</li>20       <li>手机型号:{{show.type}}</li>21       <li>市场价格:{{show.price}}</li>22     </ul>23   </template>24 25   <script>26     Vue.component('my-parent', {27       template: '#parent',28       data () {29         return {30           brand: ''31         }32       }33     })34     Vue.component('my-child', {35       template: '#child',36       data () {37         return {38           content: [39             {brand: '华为', type: 'Mate20', price: 3699},40             {brand: '苹果', type: 'iPhone7', price: 2949},41             {brand: '三星', type: 'Galaxy S8+', price: 3299},42             {brand: 'vivo', type: 'Z5x', price: 1698},43             {brand: '一加', type: 'OnePlus7', price: 2999},44             {brand: '360', type: 'N7 Pro', price: 1099},45             {brand: 'oppo', type: 'Reno', price: 2599}46           ],47           show: {brand: '', type: '', price: ''}48         }49       },50       props: ['name'],51       watch: {52         name () {53           if (this.$props.name) {54             var found = false55             this.content.forEach((value, index) => {56               if (value.brand === this.$props.name) {57                 found = value58               }59             })60             this.show = found ? found : {brand: '', type: '', price: ''}61           } else {62           return63         }64         }65       }66     })67     var vm = new Vue({68       el: '#app',69       data: {}70     })71  </script>

1.3 效果展示

2.vm.$options

Vue实例初始化时,除了传入指定的选项外,还可以传入自定义选项。自定义选项的值可以是数组、对象、函数等,通过vm.$options来获取。

2.1 实现步骤

  • 定义根标签
  • 创建vm实例
  • 在vm实例配置对象中添加$options。

2.2 代码实现

 1 <div id="app"> 2     <p>{{base}}</p> 3     <p>{{noBase}}</p> 4   </div> 5   <script> 6     var vm = new Vue({ 7       el: '#app', 8       customOption: '我是自定义数据', 9       data: {10         base: '我是基础数据' 11       },12       created () {13         this.noBase = this.$options.customOption14       }15     })16  </script>

2.3 效果展示

3.vm.$el

vm.$el用来访问vm实例使用的根DOM元素

3.1 实现步骤

  • 定义根标签
  • 修改内容

3.2 代码实现

1 <div id="app">2     <p>我是根标签结构</p>3   </div>4   <script>5     var vm = new Vue({6       el: '#app'7     })8     vm.$el.innerHTML = '<div>我是替换后的div标签</div>'9   </script>

3.3 效果展示

4.vm.$children

该属性只针对vue组件,与js中childNodes还是有区别的。

$children: 获取子组件实例集合。

childNodes: 获取子节点集合。

4.1 实现步骤

  • 定义根标签
  • 定义子组件
  • 获取子组件

4.2 代码实现

 1 <div id="app"> 2     <button @click="child">查看子组件</button> 3     <my-component></my-component> 4   </div> 5   <script> 6     Vue.component('my-component', {template: '<div>myComponent</div>'}) 7     var vm = new Vue({ 8       el: '#app', 9       methods: {10         child () {11           console.log(this.$children)12         }13       }14     })15   </script>

4.3 效果展示

5.vm.$root

vm.$root用来获取当前组件树的根Vue实例,如果当前实例没有父实例,则获取到的是该实例本身。

5.1 实现步骤

  • 创建vm实例
  • 获取根Vue实例

5.2 代码实现

 1 <div id="app"> 2     <my-component></my-component> 3   </div> 4   <script> 5     Vue.component('my-component', { 6       template: '<button @click="root">查看根实例</button>', 7       methods: { 8         root () { 9           console.log(this.$root)10           console.log(this.$root === vm.$root)11         }12       }13     })14     var vm = new Vue({ el: '#app' })15   </script>

5.3 效果展示

6.vm.$slots

Vue中的组件中使用template模板定义HTML结构,为了方便使用template公共模板结构。

Vue提出了插槽(Slots)的概念,插槽就是定义在组件内部的template模板,可以通过$slots动态获取。

案例一:通过<slot></slot>展示组件中的内容。

6.1 实现步骤

  • 定义组件模板
  • 注册my-component组件
  • 通过v-slot定义插槽对象。

6.2 代码实现

 1 <div id="app"> 2     <my-component>你好</my-component> 3   </div> 4  5   <template id="first"> 6     <div> 7       <slot></slot> 8     </div> 9   </template>10   11   <script>12     Vue.component('my-component', { template: '#first' })13     var vm = new Vue({ el: '#app' })14   </script>

6.3 效果展示

案例二:通过v-slot定义插槽对象。

6.4 实现步骤

  • 定义组件模板。
  • 注册my-component组件和打印插槽对象的文本内容。

6.5 代码实现

 1 <div id="app"> 2     <my-component>你好 3       <template v-slot:second> 4         <div>内部结构</div> 5       </template> 6     </my-component> 7   </div> 8  9   <template id="first">10     <div>11       <slot></slot>12       <slot name="second"></slot>13     </p>14   </template>15 16   <script>17     Vue.component('my-component', { template: '#first' })18     var vm = new Vue({ el: '#app' })19     // 在控制台查看插槽内容20     console.log(vm.$children[0].$slots.second[0].children[0].text)21   </script>

6.6 效果展示

7.vm.$attrs

vm.$attrs可以获取组件的属性,但其获取的属性中不包含class、style以及被声明为props的属性。

7.1 实现步骤

  • 定义id属性
  • 查看id属性

7.2 代码实现

 1 <div id="app"> 2     <my-component id="test"></my-component> 3   </div> 4   <script> 5     Vue.component('my-component', { 6       template: '<button @click="showAttrs">查看属性</button>', 7       methods: { 8         showAttrs () { 9           console.log(this.$attrs)10         }11       }12     })13     var vm = new Vue({ el: '#app' })14   </script>

7.3 效果展示

三、全局配置

1.productionTip

打开或关闭生产信息提示信息,默认为打开状态。

1.1 实现步骤

  • 设置属性值为false,表示关闭生产信息提示信息。
  • 刷新浏览器页面,查看运行结果。

1.2 代码实现

1  <script>2     Vue.config.productionTip = false3   </script>

1.3 效果展示

2.silent

silent可以取消Vue日志和警告,silent默认值为false,开启警告功能。

2.1 实现步骤

  • silent的值设置为true,可以取消Vue日志和警告。

2.2 代码实现

1 <div id="app">{{msg}}</div>2   <script>3     Vue.config.silent = true4     var vm = new Vue({ el: '#app' })5   </script>

2.3 效果展示

3.devtools

表示打开或关闭vue-devtools调试工具,默认值为true,表示vue-devtools工具可用。

3.1 实现步骤

  • devtools的值设置为false,关闭vue-devtools功能。
  • 刷新浏览器页面,查看运行结果。

3.2 代码实现

1  <script>2     Vue.config.devtools = false3   </script>

3.3 效果展示

刷新浏览器页面

四、组件进阶

1.mixins

mixins是一种分发Vue组件中可复用功能的方式。

mixins对象可以包含任何组件选项,将定义的mixins对象引入组件中即可使用,mixins中的所有选项将会混入到组件自己的选项中。

1.1 实现步骤

  • 定义myMixin对象
  • 配置mixins选项

1.2 代码实现

 1 <script> 2     // 定义myMixin对象 3     var myMixin = { 4       created () { 5         this.hello() 6       }, 7       methods: { 8         hello () { 9           console.log('hello from mixin!')10         }11       }12     }13     var Component = Vue.extend({14       mixins: [myMixin]15     })16     var component = new Component()17   </script>

1.3 效果展示

2.render

在Vue中可以使用Vue.render()实现对虚拟DOM的操作。在Vue中一般使用template来创建HTML,但这种方式可编程性不强,而使用Vue.render()可以更好地发挥JavaScript的编程能力。

2.1 实现步骤

  • 定义根标签
  • 渲染页面结构
  • 使用render()函数

2.2 代码实现

 1 <div id="app"> 2     <my-component>成功渲染</my-component> 3   </div> 4   <script> 5     Vue.component('my-component', { 6       render (createElement) { 7         return createElement('p', { 8           style: { 9             color: 'red',10             fontSize: '16px',11             backgroundColor: '#eee'12           }13         }, this.$slots.default)14       }15     })16     var vm = new Vue({ el: '#app' })17   </script>

2.3 效果展示

3.createElement

createElement()函数返回的并不是一个实际的DOM元素,它返回的其实是一个描述节点(createNodeDescription)。

  • 第1个参数可以是一个HTML标签名或组件选项对象。
  • 第2个参数是可选的,可以传入一个与模板中属性对应的数据对象。
  • 第3个参数是由createElement()构建而成的子级虚拟节点,也可以使用字符串来生成文本虚拟节点。

案例:使用render()函数渲染页面结构。

3.1 实现步骤

  • 定义插槽
  • 创建vm实例对象
  • 使用createElement()函数创建header、content和footer元素。

3.2 代码实现

 1   <div id="app"> 2     <my-component> 3       <template v-slot:header> 4         <div style="background-color:#ccc;height:50px"> 5           这里是导航栏 6         </div> 7       </template> 8       <template v-slot:content> 9         <div style="background-color:#ddd;height:50px">10           这里是内容区域11         </div>12       </template>13       <template v-slot:footer>14         <div style="background-color:#eee;height:50px">15           这里是底部信息16         </div>17       </template>18     </my-component>19   </div>20   <script>21     Vue.component('my-component', {22       render (createElement) {23         return createElement('div', [24           createElement('header', this.$slots.header),25           createElement('content', this.$slots.content),26           createElement('footer', this.$slots.footer)27         ])28       }29     })30     var vm = new Vue({ el: '#app' })31   </script>

3.3 效果展示

 

总结:

以上便是本篇文章所写的关于Vue.directive()、Vue.use()等常用全局API的使用,vm.$props、vm.$options、vm.$slots等实例属性的使用,以及Vue全局配置、组件的mixins、组件中渲染函数的使用。

通过以上的学习,各位·笔友应能够熟练使用Vue完成一些简单的页面操作。

码字不易,觉得楼主写的还不错,对你有帮助的话,请给个三连(关注、点赞、收藏)另外有问题可评论区留言讨论。

后期会完善Vue进阶语法的相关知识,有帮助的话,敬请关注楼主持续更新中ing 。。。(不定时发文)

转载时请注明出处链接

 

 参考文档:

 1.vue官方文档:Vue.js (vuejs.org)

 2.传智播客-黑马程序员(教材):http://stu.ityxb.com/


 

其他随笔推荐:

1. Vue开发环境的部署:https://www.cnblogs.com/zbcxy506/p/zbcxy506_1vue-01.html

2. Vue基础入门一:https://www.cnblogs.com/zbcxy506/p/zbcxy506_1vue-02.html

 

posted @ 2022-04-08 20:24 智博程序园 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员