zoukankan      html  css  js  c++  java
  • Vue2.0组件间数据传递

    Vue1.0组件间传递

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

    Vue2.0后$dispatch(),$broadcast()被弃用,见https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替换

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

    父组件:

    复制代码
    <template>
      <div>
        <input type="text" v-model="msg">
        <br>
        //将子控件属性inputValue与父组件msg属性绑定
        <child :inputValue="msg"></child>
      </div>
    </template>
    <style>
    
    </style>
    <script>
      export default{
        data(){
          return {
            msg: '请输入'
          }
        },
        components: {
          child: require('./Child.vue')
        }
      }
    </script
    复制代码

    子组件:

    复制代码
    <template>
      <div>
        <p>{{inputValue}}</p>
      </div>
    </template>
    <style>
    
    </style>
    <script>
        export default{
            props: {
              inputValue: String
            }
        }
    </script>
    复制代码

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

     父组件:

    复制代码
    <template>
      <div>
    //message为子控件上绑定的通知;recieveMessage为父组件监听到后的方法
        <child2 v-on:message="recieveMessage"></child2>
      </div>
    </template>
    <script>
      import {Toast} from 'mint-ui'
      export default{
        components: {
          child2: require('./Child2.vue'),
          Toast
        },
        methods: {
          recieveMessage: function (text) {
            Toast('监听到子组件变化'+text);
          }
        }
      }
    </script>
    复制代码

    子组件:

    复制代码
    <template>
      <div>
        <input type="text" v-model="msg" @change="onInput">
      </div>
    </template>
    <script>
      export default{
        data(){
          return {
            msg: '请输入值'
          }
        },
        methods: {
          onInput: function () {
            if (this.msg.trim()) {
              this.$emit('message', this.msg);
            }
          }
        }
      }
    </script>
    复制代码
  • 相关阅读:
    恭介的法则
    229. Majority Element II
    169. Majority Element
    233. Number of Digit One
    172. Factorial Trailing Zeroes
    852. Peak Index in a Mountain Array
    162. Find Peak Element
    34. Find First and Last Position of Element in Sorted Array
    81. Search in Rotated Sorted Array II
    33. Search in Rotated Sorted Array
  • 原文地址:https://www.cnblogs.com/Tohold/p/8665435.html
Copyright © 2011-2022 走看看