zoukankan      html  css  js  c++  java
  • Vue $emit $event 传值(子to父)

    事件名

    始终使用 kebab-case 的事件名。

    通过事件向父组件发送信息

    子组件中EnFontsize.vue中$emit

     <button @click="$emit('enlarge-text')">Enlarge text</button>
    

    父组件中

    <template>
      <div id="app">
        <div :style="{ fontSize: postFontSize + 'em' }">
          <div v-for="post in posts" v-bind:key="post.id" v-bind:post="post">
            <span>{{post.id}}</span>
            <span>{{post.title}}</span>
            <EnFontsize v-on:enlarge-text="postFontSize += 0.1"></EnFontsize>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    import EnFontsize from "./components/EnFontsize";
    
    export default {
      name: "App",
      data: function() {
        return {
          posts: [
            { id: 1, title: "the title is..." },
            { id: 2, title: "the title is..." }
          ],
          postFontSize: 1
        };
      },
      components: {
        EnFontsize
      }
    };
    </script>
    

    使用事件抛出一个值

    子组件中使用 $emit 的第二个参数来提供这个值:

     <button @click="$emit('enlarge-text', 0.1)">Enlarge text</button>
    

    父组件中可以通过 $event 访问到被抛出的这个值:

     <EnFontsize v-on:enlarge-text="postFontSize += $event"></EnFontsize>
    

    或者,如果这个事件处理函数是一个方法:

    <!-- <EnFontsize v-on:enlarge-text="postFontSize+=$event"></EnFon>-->
        <EnFontsize v-on:enlarge-text="onEnlargeText"></EnFontsize>
    

    那么这个值将会作为第一个参数传入这个方法:

    methods: {
      onEnlargeText: function (enlargeAmount) {
        this.postFontSize += enlargeAmount
      }
    }
    

    注意:这里是自动接收这个值并传给函数作为第一个参数,虽然没有使用$event接收

  • 相关阅读:
    ansible部署apache
    yum换源,rpm包下载,源码包安装
    zabbix 监控apache
    分块大法 -- 优雅的暴力
    [每日一题]:建立联系 -- 最小生成树
    [每日一题]:P1016 旅行家的预算 -- 反悔贪心
    [每日一题]:[NOIP2010]关押罪犯 -- 并查集
    Python基础: 元组的基本使用
    Python基础: 列表的基本使用
    Python基础:分支、循环、函数
  • 原文地址:https://www.cnblogs.com/guangzan/p/11268980.html
Copyright © 2011-2022 走看看