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。

运行结果
运行结果
扫码申请加入全栈部落
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

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

友情链接更多精彩内容