手挽手带你学VUE:二档 组件开发以及经常使用全局api

视频教程

因为思否不支持视频连接 视频请移步 http://www.henrongyi.top

你能学到什么

二档视频固然要比一档视频难一点,若是前面的内容尚未消化完毕的话,仍是建议你们继续消化前面的内容,而后再看接下来的部分。这一部分是VUE的核心,讲到组件化开发的基础部分,多学,多练。javascript

生命周期

Vue官网给出的生命周期图html

<img src='https://cn.vuejs.org/images/l...' >
这张图里包含了基本的生命周期,实际上生命周期钩子函数还有两个不在图内(activated,deactivated),这两个生命周期函数这里不给你们讲,若是你们有兴趣能够自行到VUE官网看文档,工做中用到他们的机会很少,这边讲也会扰乱你们的学习进程。这里咱们经过代码来说解Vue的生命周期vue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .active{
            color:red
        }
    </style>
</head>
<body>
    <div id="app">
        <button v-on:click="add">+</button>{{num}}<button @click="minus">-</button>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
               num:1
            },
            methods:{
                add(){
                    this.num++
                },
                minus(){
                     this.num--
                }
            },
            beforeCreate:function(){
                console.log('页面初始化以后马上执行');
            },
            created:function(){
                console.log('页面初始化完成以后created,这里模板尚未渲染呢!');
            },
            beforeMount:function(){
                console.log('组件挂载以前beforeMount');
            },
            mounted:function(){
                console.log('组件挂载以后mounted');
            },
            beforeUpdate:function(){
                console.log('组件更新前beforeUpdate');
            },
            updated:function(){
                console.log('组件更新后updated');
            },
        //   activated:function(){
        //      console.log('activated');
        //    },
        //    deactivated:function(){
        //        console.log('deactivated');
        //    },    你只须要知道这两个生命周期是在这个位置进行就行了,别的能够不要想太多。
            beforeDestroy:function(){
                console.log('组件销毁以前beforeDestroy');
            },
            destroyed:function(){
                console.log('组件销毁后destroyed')
            }
        })
    </script>
</body>
</html>

这些生命周期函数大致就演示到这里,剩下的两个没能给你们展现的请你们牢记,咱们开始学组件的时候,就能够体会到这两个钩子函数的用法了。java

组件建立

Vue.component
注册全局组件
Vue.component("组件名",{ 组件的各类属性(模板啊,data啊,方法啊,生命周期啊之类的。) }), (视频里有一句口误,应该是小驼峰。手动捂脸)node

这个全局API看过之后,咱们来实现一个组件的hello worldvue-cli

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
       <shuai-qm></shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        Vue.component("shuai-qm",{
            data(){
                return{
                    hello:'hello world'
                }
            },
            template:'<h1>{{hello}}</h1>'
        })
        
        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello Word',
                isTrue:true,
            },
        })
    </script>
</body>
</html>

一个全局组件的hello world就完成了,可是你们是否是以为全局组件很是不踏实?随时可能一个变更摧毁咱们的项目?
那不要紧,接下来是局部组建的注册方法。express

Vue的components属性npm

咱们在注册局部组建的时候,须要把局部组建挂载到Vue构造器的components内,注意:全局api不带s,而这个属性带s。不说废话,咱们先来构造一个。api

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
    {{message}}
       <shuai-qm></shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
              components:{
                   "shuaiQm":{
                       data(){
                           return{
                               hello:"hello world"
                           }
                       },
                       template:'<h1>{{hello}}</h1>'
                       }
                }
            
        })
    </script>
</body>
</html>

这样咱们就获得了一个能够hello world的局部组件,可是,一堆组建都这个样子罗列出来的话,会将咱们的项目弄得体无完肤?
因此咱们抽离一下代码。变成这样数组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
    {{message}}
      <shuai-qm></shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var shuaiQm = {
            data(){
                return{
                    hello:"hello world"
                }
            },
            template:'<h1>{{hello}}</h1>'
            }


        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":shuaiQm,
            }
        })
    </script>
</body>
</html>

是否是用vue-cli开发过的同窗就比较眼熟了?那么问题又来了,组件里面的html全都是写的字符串,都这么玩下去,要乱死啊,没问题,咱们继续抽离。

这里介绍的就是vue的template用法了,立刻又是一个cli党眼熟的东西

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<template id="shuaiQm">
    <h1>{{hello}}</h1>
</template>

<!-- 上面是html模板的用法,下面是script模板的用法,使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。-->

<!-- 推荐 -->
<script type="x-template" id="shuaiQm2">
    <h2 style="color:blue">{{hello}}</h2>
</script>

<body>
    <div id="app">
    {{message}}
       <shuai-qm></shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var shuaiQm = {
            data(){
                return{
                    hello:"hello world"
                }
            },
            template:"#shuaiQm2"
            }


        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":shuaiQm,
            }
        })
    </script>
</body>
</html>

拆出来之后是否是莫名其妙引发了极度温馨?固然后面咱们学到使用vue-cli的时候 咱们还会用到新的书写方法 .vue 文件的方法,这里就先不给你们多说了。

组件里面套组件(父子组件)

可能由同窗会问了,组件里面还能够嵌套组件吗?我能够很负责任地告诉你,彻底没问题!怎么写呢?你若是会在Vue实例的构造器里引用组件,你就会在别的组件内部引用组件,他们实际上是一个写法。这边我使用咱们的第三种模板写法来给你们书写。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="father">
  <div>
    <h2 style="color:blue">{{hello}}</h2>
    <childer  />
  </div>
</script>

<script type="x-template" id="childer">
    <h2 style="color:blue">{{hello}}</h2>
</script>

<body>
    <div id="app">
    {{message}}
    <shuai-qm></shuai-qm>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var childer = {
            data(){
                return{
                    hello:"hello i'm dawangraoming"
                }
            },
            template:"#childer"
        }


        var father = {
            data(){
                return{
                    hello:"hello world"
                }
            },
            template:"#father",
            components:{
                "childer":childer
            }
            }




        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":father,
            }
        })
    </script>
</body>
</html>

这里你们也能够看到,咱们在 app内部只引用了 shuaiQm这一个组件, shuaiQm又包含他的子组件 childer,所以父子都被渲染出来了。这就是父子组件的写法。

插槽slot

这时候又有朋友要问了,若是我想在组件里面继续书写html怎么办呢? slot插槽就是个很好的东西了,这里我用代码给你们演示一下slot插槽的用法。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="shuaiQm2">
    <div style="color:blue">
        <h2>{{hello}}</h2>
        <solt name="solt1">我是插槽solt1</solt>
        <solt name="solt2">我是插槽solt2</solt>
        <!-- 若是插槽不使用的话,内部的默认文字就会展现出来 -->
    </div>
</script>

<body>
    <div id="app">
    {{message}}
       <shuai-qm>
           <span slot="solt1">hello world</span>
       </shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var shuaiQm = {
            data(){
                return{
                    hello:"hello world"
                }
            },
            template:"#shuaiQm2"
            }


        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":shuaiQm,
            }
        })
    </script>
</body>
</html>

插槽只有这一个做用吗?不,那你就过小看插槽了,接下来要介绍一下插槽的做用域插槽用法。

做用域插槽,听不懂可跳过,后面还会详细讲解

使用时候子组件标签Child中要有 template scope=”scopeName” 标签,再经过scopeName.childProp就能够调用子组件模板中的childProp绑定的数据,因此做用域插槽是一种子传父传参的方式,解决了普通slot在parent中没法访问child数据的去问题;
这么说太复杂了,直接上个例子显而易见。
若是这里听不懂能够暂时跳过,只须要会用slot插槽的基础用法便可,在后面讲Element项目的时候,我会结合实例给你们讲解这个做用域插槽。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="shuaiQm2">
    <div style="color:blue">
        <h2>{{hello}}</h2>
        <slot name="item" v-for="item in items" :text="item.text" :myname="item.myname" >
            slot的默认内容
        </slot>
    </div>
</script>

<body>
    <div id="app">
    {{message}}
       <shuai-qm>
          <template slot="item" scope="props">
            <li>{{props.myname}}</li>
            <li>{{props.text}}</li>
          </template>
       </shuai-qm>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var shuaiQm = {
            data(){
                return{
                    hello:"hello world",
                    items:[{
                      text:"我在子组件内,经过插槽展现在父组件",
                      myname:"Qm",
                    },{
                      text:"我在子组件内,经过插槽展现在父组件",
                      myname:"奇淼",
                    }]
                }
            },
            template:"#shuaiQm2"
            }


        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":shuaiQm,
            }
        })
    </script>
</body>
</html>

prop 传递参数给组件(父传值给子)

讲到这里,已经到了VUE一个须要理解的地方了,父子传值,咱们先讲解一下,如何将值传递给子组件,这个总体来讲仍是比较简单。引用咱们的组件的标签上写上属性,而且把参数传入,这样咱们在组件内部使用props就能够得到传过来的值了,咱们仍是以上面的代码为例。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="father">
  <div>
    <h2 style="color:blue">{{hello}}</h2>
    {{apptoshuaiqm}}
    <childer :shuai-qmtochilder="shuaiQmGiveMe" />
  </div>
</script>

<script type="x-template" id="childer">
    <div>
        <h2 style="color:blue">{{hello}}</h2>
        {{shuaiQmtochilder}}
    </div>
</script>

<body>
    <div id="app">
    <shuai-qm apptoshuaiqm="我是app传过来的值" ></shuai-qm>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var childer = {
          props:['shuaiQmtochilder'],
            data(){
                return{
                    hello:"hello i'm dawangraoming",
                }
            },
            template:"#childer"
        }


        var father = {
            props:["apptoshuaiqm"],// 这里你们必定要注意,请彻底使用小写传参
            data(){
                return{
                    hello:"hello world",
                    shuaiQmGiveMe:"我是从shuaiQm传过来的值"
                }
            },
            template:"#father",
            components:{
                "childer":childer
            }
            }




        var app = new Vue({
            el:"#app",
            data:{
                message:'Hello World',
                isTrue:true,
            },
            components:{
                   "shuaiQm":father,
            }
        })
    </script>
</body>
</html>

这一段代码注意,再给html上面添加属性的时候,咱们是不能够直接添加驼峰命名的,由于html不会区分大小写,因此咱们建议属性的命名方式是彻底小写或者横线命名的方式。若是咱们使用横线命名来传递参数的话,在接收的时候,横线后面的首字母大写,变成小驼峰来接受,不然使用的时候它会被渲染成NaN,这是为何呢?别忘了咱们一档讲过的,在插值表达式内,是支持简单计算的,- 会被看成减号处理,这里我会在视频中给你们详细讲解。

子组件传值给父组件

学到这里,若是你们已经有些迷茫,如今请先停下,喘口气,这里难度已经慢慢加大。我也会放慢讲解的速度。
若是咱们想要获取到子组件内部的值,该怎么办呢?有什么办法可以让咱们回去到内部的值呢?在这里,先给你们插播一个JS写法,我以为这有助于理解子传父值。

function thief (gold) {
    console.log(gold)
}

function richMan (){
    var money = 1000086
    thief(money)
}

richMan()

咱们想要在vue中作到子传参给父,那咱们的父组件就要像子组件伸出小偷之手。我在代码中为你们书写一下

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="shuaiQm">
  <div>
   
  </div>
</script>

<body>
    <div id="app">
      {{qmGold}}
    <shuai-qm :father="thief"></shuai-qm>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var shuaiQm = {
            props:["father"],
            data(){
                return{
                    money:"10000",
                }
            },
            template:"#shuaiQm",
            created() {
              this.father(this.money)
            },
            }



        var app = new Vue({
            el:"#app",
            data:{
              qmGold:0,
            },
            components:{
                   "shuaiQm":shuaiQm,
            },
            methods:{
              thief(gold){
                this.qmGold = gold
              }
            }
        })
    </script>
</body>
</html>

这样 你理解子传参给父了吗?

其他会用到的全局API

Vue.directivet
Vue.directive 咱们用来编写全局指令,它也有本身的生命周期

// 注册
Vue.directive('my-directive', {
  bind: function () {},
  inserted: function () {},
  update: function () {},
  componentUpdated: function () {},
  unbind: function () {}
})

/*
bind:只调用一次,指令第一次绑定到元素时调用。在这里能够进行一次性的初始化设置。

inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不必定已被插入文档中)。

update:所在组件的 VNode 更新时调用,可是可能发生在其子 VNode 更新以前。指令的值可能发生了改变,也可能没有。可是你能够经过比较更新先后的值来忽略没必要要的模板更新 (详细的钩子函数参数见下)。

componentUpdated:指令所在组件的 VNode 及其子 VNode 所有更新后调用。

unbind:只调用一次,指令与元素解绑时调用。

接下来咱们来看一下钩子函数的参数 (即 el、binding、vnode 和 oldVnode)。

在这些钩子函数内部,均可以接受三个参数,咱们来看看文档中的写法。
el:指令所绑定的元素,能够用来直接操做 DOM 。

binding:一个对象,包含如下属性:
    name:指令名,不包括 v- 前缀。
    value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
    oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。不管值是否改变均可用。
    expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
    arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
    modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
vnode:Vue 编译生成的虚拟节点。
oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

这里我会在视频中结合官方样例讲解
*/

上面咱们罗列了这么多它的特性,不过真正开发中,咱们最经常使用的只有 bind 和 update 这两个时期
咱们能够简写为

Vue.directive('color', function (el, binding) {
        el.style.backgroundColor = binding.value
    })

下面咱们来举个例子

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script type="x-template" id="shuaiQm">
  <div>
   
  </div>
</script>

<body>
    <div id="app">
      <div v-color="color">
          我来测试测试directive
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        Vue.directive("color",function(el,binding){
            el.style.color = binding.value
        })

        var app = new Vue({
            el:"#app",
            data:{
                color:"red"
            }
        })
    </script>
</body>
</html>

好了咱们能够看到加上v-color的这个div内部的文字变红了

Vue.set

Vue.set官网给出的用法是 Vue.set( target, key, value ) 向响应式对象中添加一个属性,并确保这个新属性一样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,由于 Vue 没法探测普通的新增属性
这么听起来是有些笼统的,我给你们用代码展现一下它在咱们平常开发中常常出现的场景。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
      <ul>
        <li v-for="(item,ket) in list" :key="key">{{item.hello}}</li>
      </ul>
      <button @click="addList">+</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var app = new Vue({
            el:"#app",
            data:{
                list:[{hello:"hello world"},{hello:"hello two"}]
            },
            methods:{
                addList(){
                   this.list[0] = {hello:"ttt"}
                    console.log(this.list)
                }
            }
        })
    </script>
</body>
</html>

在上述代码中,咱们经过this.list[0]直接修改了数组中的第0项目对象,那么视图是没有更新的,可是数据确实变动了,这是为何呢?由于Vue是经过Object.defineProperty()来进行数据的监听,它的机制致使了它没法直接检测出数组中这种状况的变化。这时候咱们就须要使用Vue.set了

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
      <ul>
        <li v-for="(item,ket) in list" :key="key">{{item.hello}}</li>
      </ul>
      <button @click="addList">+</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var app = new Vue({
            el:"#app",
            data:{
                list:[{hello:"hello world"},{hello:"hello two"}]
            },
            methods:{
                addList(){
                   this.list[0] = {hello:"ttt"}
                    console.log(this.list)
                }
            }
        })
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
      <ul>
        <li v-for="(item,ket) in list" :key="key">{{item.hello}}</li>
      </ul>
      <button @click="addList">+</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var app = new Vue({
            el:"#app",
            data:{
                list:[{hello:"hello world"},{hello:"hello two"}]
            },
            methods:{
                addList(){
                //    this.list[0] = {hello:"ttt"}
                    Vue.set(this.list,0, {hello:"我强制改变了!"})
                    // this.$set(this.list,0,{hello:"我强制改变了!"})  在methods 中能够写成 this.$set 
                    console.log(this.list)
                }
            }
        })
    </script>
</body>
</html>

看 是否是强制将它改变了呢? 有了Vue.set 数据就都再也不得瑟了

相关文章
相关标签/搜索