vue组件详解

什么是组件:

组件是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。在较高层面上,组件是自定义的元素,Vue.js的编译器为它添加特殊功能。在有些情况下,组件也可以是原生HTML元素的形式,以is特性扩展。

  • 如何注册组件?
    需要使用Vue.extend方法创建一个组件,然后使用Vue.component方法注册组件。Vue.extend方法格式如下:
-->vue1.0
var MyComponent = Vue.extend({
    template: '
A custom component!
' }) -->vue2.0 var MyComponent = { template: '
A custom component!
' }

如果想要其他地方使用这个创建的组件,还得个组件命个名:
Vue.component('my-component', MyComponent)
命名之后即可在HTML标签中使用这个组件名称,像使用DOM元素一样。下面来看看一个完整的组件注册和使用例子。

全局组件
// 定义 var MyComponent = Vue.extend({ template: '
A custom component!
' }) // 注册 Vue.component('my-component', MyComponent) // 创建根实例 new Vue({ el: '#app' }) 局部组件 var myComponent = Vue.extend({ template: '
This is my first component!
' }) new Vue({ el: '#app', components: { // 2. 将myComponent组件注册到Vue实例下 'my-component' : myComponent } });
  • 嵌套组件

组件本身也可以包含组件,下面的parent组件就包含了一个命名为child-component组件,但这个组件只能被parent组件使用:

var child = Vue.extend({
 template: '
A custom component!
' }); var parent = Vue.extend({ template: '
Parent Component:
', components: { 'child-component': child } }); Vue.component("parent-component", parent);

上面的定义过程比较繁琐,也可以不用每次都调用Vue.component和Vue.extend方法:

// 在一个步骤中扩展与注册
Vue.component('my-component', {
template: '
A custom component!
' }) // 局部注册也可以这么做 var Parent = Vue.extend({ components: { 'my-component': { template: '
A custom component!
' } } })
  • 动态组件

多个组件可以使用同一个挂载点,然后动态的在他们之间切换。使用保留的元素,动态地绑定到它的is特性。下面的列子在同一个vue实例下挂了home、posts、archive三个组件,通过特性currentView动态切换组件显示。


var vue = new Vue({ el:"#dynamic", data: { currentView: "home" }, components: { home:{ template: "Home" }, posts: { template: "Posts" }, archive: { template: "Archive" } } }); document.getElementById("home").onclick = function(){ vue.currentView = "home"; }; document.getElementById("posts").onclick = function(){ vue.currentView = "posts"; }; document.getElementById("archive").onclick = function(){ vue.currentView = "archive"; };
  • 组件的el和data选项

传入Vue构造器的多数选项也可以用在 Vue.extend() 或Vue.component()中,不过有两个特例: data 和el。
Vue.js规定:在定义组件的选项时,data和el选项必须使用函数。

Vue.component('my-component', {
    data: function(){
        return {a : 1}
    }
})

vue组件之间的数据传输

Vue1.0组件间传递

  使用$on()监听事件;
  使用$emit()在它上面触发事件;
  使用$dispatch()派发事件,事件沿着父链冒泡;
  使用$broadcast()广播事件,事件向下传导给所有的后代

Vue2.0后$dispatch(),$broadcast()被弃用
  • 使用props

组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。

1,父组件向子组件传递场景:Father上一个输入框,根据输入传递到Child组件上。

父组件



子组件



2,子组件向父组件传值场景:子组件上输入框,输入值改变后父组件监听到,弹出弹框

父组件


子组件


vue组件solt内容分发

  • 概述:
    简单来说,假如父组件需要在子组件内放一些DOM,那么这些DOM是显示、不显示、在哪个地方显示、如何显示,就是slot分发负责的活。

将放在子组件里的不同html标签放在不同的位置
父组件在要分发的标签里添加 slot=”name名” 属性
子组件在对应分发的位置的slot标签里,添加name=”name名” 属性,

然后就会将对应的标签放在对应的位置了。


this is slot01
this is slot02
this is a simple div01
this is a simple div02

你可能感兴趣的:(vue组件详解)