vuejs - 父组件调用子组件的变量

访问量: 147

没有直接的办法.  参考:https://stackoverflow.com/questions/40410332/vuejs-access-child-components-data-from-parent

所以,根据官方文档:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6

1. 在子组件中,定义好watch,对应 child data var

2. child data var 一变动,立刻通过watch, 来调用 this.$emit("some_event")

3. parent中,调用child的时候,对prop进行 .sync 修饰符

Parent中的代码:

<SelectForProvince v-bind:propProvinceId.sync='province_id'></SelectForProvince>

Child的代码:

<template>
  <div>
    <el-select v-model='province_id' style='width: 100%'>
      <el-option v-for='province in provinces' :key='province.id' :label='province.name' :value='province.id'>
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  data() {
    return{
      provinces: [],
      // 初始化的选择的省份id
      province_id: this.propProvinceId
    }
  },

  watch: {
    // 监听prop, 每次该component被重新渲染的时候,都需要重新设置 this.province_id
    propProvinceId: function(new_value){
      this.init()
    },
    // 每次改动input的值,都更新 parent 中的变量
    province_id: function(new_value) {
      this.$emit('update:propProvinceId', new_value)
    }

  },
  props: ['propProvinceId'],
  .....

所以,可以认为:

<SelectForProvince v-bind:propProvinceId.sync='province_id'></SelectForProvince>

等同于

<SelectForProvince v-bind:propProvinceId='province_id' v-on:update:propProvinceId="propProvinceId=$event"></SelectForProvince>

订阅/RSS Feed

Subscribe

分类/category