Vue组件传值

父组件向子组件传值

父组件向子组件传值的方式通常是通过子组件定义的props来完成的。子组件定义props作为传入的数据,父组件应用子组件时绑定props,就能够动态地改变props的值,实现实时传值。

Son.vue

<template>
  <div>
    <span>{{msg}}span>
  div>
template>
<script>
export default {
  name: 'Son',
  props: {
    msg: String   //定义了props及其类型
  }
}
script>

Father.vue

<template>
  <div>
      <Son :msg="myMsg">Son>
      <input type="text" v-model="myMsg">
  div>
template>
<script>
import Son from './Son.vue'
export default {
  components: {
    Son
  },
  data () {
    return {
      myMsg: 'Welcome to Your Vue.js App'
    }
  }
}
script>

Son组件定义了props(msg)且类型为String,Father组件引用了Son组件,并传入Mymsg作为props值。Father组件还用Input组件绑定了myMsg,这样在Input中输入时,Son组件也会发生更新。

子组件向父组件传值

子组件向父组件传值一般通过 emit e m i t 事 件 , 出 发 emit事件,会将参数一同传到监听器的回调。一般有子组件出发 emit e m i t 事 件 并 传 值 , 由 父 组 件 监 听 。 一 个 emit事件对应使用一个时间名。

Son.vue

<template>
  <div>
    <span>{{msg}}span>
    <button @click='sendtoFather'>clearbutton>
  div>
template>
<script>
export default {
  name: 'Son',
  data () {
    return {}
  },
  props: {
    msg: String
  },
  methods: {
    sendtoFather: function () {
      this.$emit('clear')
    }
  }
}
script>

在子组件代码中加入向父组件发送消息的事件

<button @click='sendtoFather'>clearbutton>

该事件见用于清空父组件的myMsg值

父组件也对应添加了事件监听,v-on:clear=’clear’

Father.vue

<template>
  <div>
      <Son :msg="myMsg" v-on:clear='clear'>Son>
      <input type="text" v-model="myMsg">
  div>
template>
<script>
import Son from './Son.vue'
export default {
  components: {
    Son
  },
  data () {
    return {
      myMsg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    clear: function () {
      this.myMsg = ''
    }
  }
}
script>

兄弟组件传值

兄弟组件传值可以通过共同的父组件作为桥梁来实现,子组件A通过$emit事件将值传到父组件,父组件再通过Props来把值传给子组件B,具体的实现过程参照前面的方法。

你可能感兴趣的:(Vue)