Vue-组件的传值

父组件 => 子组件

  • 父组件 Father.vue
// 使用 v-bind 来动态传递 prop
<Child :toChild="This is to Child!" />
  • 子组件 Child.vue
<h1>{{ toChild }}</h1>
// 用一个 props 选项将其包含在子组件可接受的 prop 列表中
props: {
  toChild: {
    type: String,
    default: null
  }
}

子组件 => 父组件

方式一、$emit + v-on 方式传值

  • 子组件 Child.vue
// 通过调用内建的 $emit 方法并传入事件名称 fromChild 来触发一个事件,并传值,值可省略
<input @click="$emit('fromChild', 'this is to Father!')" />
// 或定义一个方法进行更多的操作
<input @click="toFather()" />
methods: {
  toFather() {
    // 定义一个方法 fromChild
    this.$emit("fromChild", "hello, this is from child!");
  }
}
  • 父组件 Father.vue
// 通过 v-on 监听子组件实例的任意事件:
// 我们可以用 $event 来接收子组件传过来的值
<Child @fromChild="this.message= $event" />
// 或定义一个方法进行更多的操作
<Child @fromChild="getChild" />
data() {
  return {
    message: null
  }
}

methods: {
  // 方法可接收一个参数,该参数即子组件传的值
  getChild(fromFa) {
    console.log(fromFa)
  }
}

方式二、props + v-bind 方式传值

  • 父组件 Father.vue
// 父组件将方法传值给子组件,让子组件触发该方法
<Child :fromChild="getChild" />
methods: {
  // fromChild 需要从子组件获得
  getChild(fromChild) {
    console.log(fromChild)
  }
}
  • 子组件 Child.vue
// 触发方法,并传入子组件的数据
<input type="button" @click="fromChild(hello)" />
data() {
  return {
    hello: 'hello, this is from child!'  
  }
}

// 通过 props 接收父组件的方法
props: {
  fromChild: {
    type: Function,
    default: () => {}
  }
}

兄弟组件间的传值

方式一:eventBus

  • Vue实例 event.js
// 创建一个vue实例,让各个兄弟共用同一个事件机制
import Vue from 'vue'
export default new Vue
  • 组件A BrotherA.vue
<input @click='toB' />
// 引入 event.js
import eventVue from 'event.js'
methods: {
  toB() {
    eventBus.$emit('toB', 'this is from A!')
  }
}
  • 组件B BrotherB.vue
// 引入 event.js
import eventVue from 'event.js'
created() {
  eventBus.$on('toB',(fromA)=>{
    console.log(fromA)
  })
}

方式二:Vuex

  • store对象
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

var store = new Vuex.Store({
    state:{
        toB: ''
    },
    mutations: {
      // 向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)
      // 在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
      hello(state, fromA) {
        state.toB = fromA.value
      }
    }
});

export default store;
  • 组件A BrotherA.vue
<input type="button"@click="toB">
import store from "../store";
data() {
  return {
    fromA: {
      value: 'hello, this if form A!'
    }
}
store:store,
methods: {
  toB() {
    store.commit('hello', this.fromA)
  }
}
  • 组件B BrotherB.vue
<h1>{{ fromA }}</h1>
import store from "../store";
store,
computed: {
  fromA() {
    return this.$store.state.toB
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。