vue 组件(下篇)

自定义事件

父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!

使用 v-on 绑定自定义事件

每个 Vue 实例都实现了事件接口 (Events interface),即:

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName) 触发事件
<div id="counter-event-example">
    <p>{{ total }}</p>
    <button-counter v-on:increment="incrementTotal"></button-counter>
    <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

<script>
    Vue.component('button-counter', {
        template: '<button v-on:click="increment22">{{ counter }}</button>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            increment22: function () {
                this.counter += 1
                console.log("button-counter-------increment")
                this.$emit('increment')
            }
        },
    })
    new Vue({
        el: '#counter-event-example',
        data: {
            total: 0
        },
        methods: {
            incrementTotal: function () {
                console.log("example-------increment")
                this.total += 1
            }
        }
    })
</script>

运行结果:

运行结果
运行结果

运行过程:

点击【按钮】,触发increment22方法,this.$emit('increment') 然后调用起Vue中的 incrementTotal方法。

button-counter-------increment
example-------increment

给组件绑定原生事件

有时候,你可能想在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰 v-on。

<div id="example-1">
    <my-component v-on:click.native="doTheThing"></my-component>
</div>
  
<script>
    Vue.component('my-component',{
        template: '<button> 点击 </button>',
    })

    new Vue({
        el: '#example-1',
        methods: {
            doTheThing: function(){
                alert("root  1111");
            }
        }
    })

</script>
    

运行结果:

 点击按钮,弹出提示框 'root  1111'

.sync 修饰符

.sync 修饰符只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 侦听器。

<comp :foo.sync="bar"></comp>

会被扩展为:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

this.$emit('update:foo', newValue)

实例:

<div id="example-2">
    <comp :foo.sync="bar"></comp> bar: {{bar}}
</div>

<script>
    Vue.component('comp', {
        props: ['foo'],
        template: '<div><input type="text" :value="foo" @input="updateData($event)"></div>',
        methods:{
            updateData: function(event){
                this.$emit('update:foo', event.target.value)
            }
        }
    })
    new Vue({
        el: '#example-2',
        data: {
            bar: '12312'
        }
    })

</script>

运行结果:输入框里面值改变,bar的值也会跟着相应的修改。

运行结果
运行结果

使用自定义事件的表单输入组件

自定义事件可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。

<currency-input v-model="price"></currency-input>

它相当于下面的简写:

<currency-input
    v-bind:value="price"
    v-on:input="price = arguments[0]">
</currency-input>

实例:

<div id="example-3">
    <currency-input label="Price" v-model="price"></currency-input>
    <p>Total: ${{ total }}</p>
</div>

<script>
    Vue.component('currency-input', {
        template: '\
    <div>\
      <label v-if="label">{{ label }}</label>\
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
        v-on:focus="selectAll"\
        v-on:blur="formatValue"\
      >\
    </div>\
  ',
        props: {
            value: {
                type: Number,
                default: 0
            },
            label: {
                type: String,
                default: ''
            }
        },
        mounted: function () {
            this.formatValue()
        },
        methods: {
            updateValue: function (value) {
                var result = { 'value': parseInt(value) }
                if (result.warning) {
                    this.$refs.input.value = result.value
                }
                this.$emit('input', result.value)
            },
            formatValue: function () {
                this.$refs.input.value = parseInt(this.value)
            },
            selectAll: function (event) {
                // Workaround for Safari bug
                // http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome
                setTimeout(function () {
                    event.target.select()
                }, 0)
            }
        }
    })

    new Vue({
        el: '#example-3',
        data: {
            price: 0,
            shipping: 0,
            handling: 0,
            discount: 0
        },
        computed: {
            total: function () {
                return ((
                    this.price * 100 +
                    this.shipping * 100 +
                    this.handling * 100 -
                    this.discount * 100
                ) / 100).toFixed(2)
            }
        }
    })

</script>

非父子组件通信

有时候两个组件也需要通信 (非父子关系)。在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()
// 在组件 B 创建的钩子中监听事件
bus.$on('msg-to-a', msg => this.message = msg );
// 触发组件 A 中的事件
bus.$emit('msg-to-a',event.target.value);

实例:

<div id="example-4">
    <input v-model='msg1' v-on:input="updateMsg($event)" />
</div>
<div id="example-5">
    <span>{{message}}</span>
</div>

<script>
    var bus = new Vue()

    new Vue({
        el: '#example-4',
        data:{
            msg1: '',
        },
        methods:{
            updateMsg: function(event){
                bus.$emit('msg-to-a',event.target.value);
            }
        }
        
    })

    new Vue({
        el: '#example-5',
        created () {
            console.log('example-5......');
            bus.$on('msg-to-a', msg => this.message = msg );
        },
        data:{
            message: 'example-5'
        }
    })


</script>

运行结果:输入框输入什么内容,下面就会显示相同的内容

运行结果
运行结果

使用 Slot 分发内容

在使用组件时,我们常常要像这样组合它们:

<app>
  <app-header></app-header>
  <app-footer></app-footer>
</app>

为了让组件可以组合,我们需要一种方式来混合父组件的内容与子组件自己的模板。这个过程被称为 内容分发 (或 “transclusion” 如果你熟悉 Angular)。

编译作用域

在深入内容分发 API 之前,我们先明确内容在哪个作用域里编译。假定模板为:

<child-component>
  {{ message }}
</child-component>

message 应该绑定到父组件的数据,还是绑定到子组件的数据?答案是父组件。组件作用域简单地说是:
父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译.

<div id="example-7">
    <child-component2>
        <div> message: {{message}}</div>
    </child-component2>
</div>

<script>

    Vue.component('child-component2', {
        template: '<div><h2>我是子组件的标题</h2><slot>只有在没有要分发的内容时才会显示。</slot>message: {{message}}</div>',
        data: function () {
            return {
                message: '12345678'
            }
        }
    })

    new Vue({
        el: '#example-7',
        data: {
            message: 'parent message'
        }
    })

运行结果:

<div id="example-7">
<div>
<h2>我是子组件的标题</h2>
<div> message: parent message</div>
message: 12345678
</div>
</div>

子组件的message 绑定的是父组件的数据。

<child-component2>
    //获取的是父组件的数据
    <div> message: {{message}}</div>
</child-component2>

//message 获取是子组件的数据
    Vue.component('child-component2', {
        template: '<div><h2>我是子组件的标题</h2><slot>只有在没有要分发的内容时才会显示。</slot>message: {{message}}</div>',
        data: function () {
            return {
                message: '12345678'
            }
        }
    })

单个 Slot

除非子组件模板包含至少一个 <slot> 插口,否则父组件的内容将会被丢弃。当子组件模板只有一个没有属性的 slot 时,父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身。


<div id="example-6">
    <child-component></child-component>
</div>

<script>
    Vue.component('child-component',{
        template: '<div><h2>我是子组件的标题</h2><slot>只有在没有要分发的内容时才会显示。</slot></div>'
    })

    new Vue({
        el: '#example-6'
    })
</script>

运行结果:

<div>
<h2>我是子组件的标题</h2>
只有在没有要分发的内容时才会显示。
</div>

如果子模版里面包含内容,那结果会怎么样?

<div id="example-6">
    <child-component>
        <div>我在这,你在哪</div>
    </child-component>
</div>

运行结果:

<div>
<h2>我是子组件的标题</h2>
<div>我在这,你在哪</div>
</div>

具名 Slot

<slot> 元素可以用一个特殊的属性 name 来配置如何分发内容。多个 slot 可以有不同的名字。具名 slot 将匹配内容片段中有对应 slot 特性的元素。

<div id="example-8">
    <app-layout>
        <h1 slot="header">这里可能是一个页面标题</h1>
        <p>主要内容的一个段落。</p>
        <p>另一个主要段落。</p>
        <p slot="footer">这里有一些联系信息</p>
    </app-layout>
</div>

<script>

    Vue.component('app-layout',{
        template: '<div class="container">\
  <header>\
    <slot name="header"></slot>\
  </header>\
  <main>\
    <slot></slot>\
  </main>\
  <footer>\
    <slot name="footer"></slot>\
  </footer>\
</div>'
    })

    new Vue({
        el: '#example-8'
    })
</script>

运行结果:

<div id="example-8">
<div class="container">
<header><h1>这里可能是一个页面标题</h1>
</header> 
<main> <p>主要内容的一个段落。</p> <p>另一个主要段落。</p> </main> 
<footer><p>这里有一些联系信息</p></footer>
</div>
</div>

作用域插槽

作用域插槽是一种特殊类型的插槽,用作使用一个 (能够传递数据到) 可重用模板替换已渲染元素。

    <div  id="example-9" class="parent">
        <child>
            <template scope="props">
                <span>hello from parent</span>
                <span>{{ props.text }}</span>
            </template>
        </child>
    </div>
    
<script>
    Vue.component('child',{
        template: '<div class="child"><slot text="hello from child"></slot></div>'
    })

    new Vue({
        el: '#example-9'
    })
</script>

运行结果:

<div id="example-9" class="parent">
<div class="child">
<span>hello from parent</span> 
<span>hello from child</span>
</div>
</div>

动态组件

通过使用保留的 <component> 元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换:

    <div id="example-10">
        <component v-bind:is="currentView">
            <!-- 组件在 vm.currentview 变化时改变! -->
        </component>
    </div>
    
<script>
    
    var Home = {
        template: '<p>Welcome home!</p>'
    }

    var Home2 = {
        template: '<p>Welcome home2!</p>'
    }

    var Home3 = {
        template: '<p>Welcome home3!</p>'
    }

    var vm10 = new Vue({
        el: '#example-10',
        data: {
            currentView: Home
        }
    })

</script>

运行结果:

Welcome home!

如果在谷歌浏览器控制台输入 
vm10.currentView = Home2

运行结果变为:
Welcome home2!
运行结果
运行结果

keep-alive

    <div id="example-11">
        <keep-alive>
        <component v-bind:is="currentView">
            <!-- 组件在 vm.currentview 变化时改变! -->
        </component>
        </keep-alive>
    </div>

<script>
    var Home11 = {
        template: '<p>Welcome home11!</p>',
        created(){
            console.log('fetch data home11')
        }
    }

    var Home22 = {
        template: '<p>Welcome home22!</p>',
        created(){
            console.log('fetch data home22')
        }
    }


    var vm11 = new Vue({
        el: '#example-11',
        data: {
            currentView: Home11
        }
    })

</script>

运行结果:

第一次页面加载时,会打印 fetch data home11 ,切换到home22,会打印 fetch data home22, 再切换到home11,就不会打印 fetch data home11。

运行结果
运行结果
扫码申请加入全栈部落
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容

  • 此文基于官方文档,里面部分例子有改动,加上了一些自己的理解 什么是组件? 组件(Component)是 Vue.j...
    陆志均阅读 3,790评论 5 14
  • 1.安装 可以简单地在页面引入Vue.js作为独立版本,Vue即被注册为全局变量,可以在页面使用了。 如果希望搭建...
    Awey阅读 10,971评论 4 129
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 什么是组件 组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用...
    angelwgh阅读 774评论 0 0
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,040评论 0 29