Parent monitoring Child triggering

by Irene Tang

HTML

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@1.4.1/lib/index.js"></script>
<script id="child" type="x-template">
  <el-dialog v-model="visible"
    title="子组件">
    <div>
      <el-select v-model="selected">
        <el-option v-for="(opt, index) in options" :key="index" :label="opt.label" :value="opt.value">
        </el-option>
      </el-select>
    </div>
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</script>

<div id="parent">
  <el-button @click="openDialog">打开弹框</el-button>
  <div>{{ text }}</div>
  <child ref="child" @dialog-confirm="getSelected"></child>
</div>

CSS

@import url("//unpkg.com/element-ui@1.4.1/lib/theme-default/index.css");

JavaScript

var Child = {
  template: '#child',
  data () {
    return {
      visible: false,
      selected: 1,
      options: [
        {
          label: '选项1',
          value: 1
        }, {
          label: '选项2',
          value: 2
        }
      ]
    }
  },
  methods: {
    open () {
      this.visible = true
    },
    close () {
      this.visible = false
    },
    confirm () {
      this.$emit('dialog-confirm', this.selected)
      this.close()
    }
  }
}
var Parent = {
  data () {
  	return {
      text: ''
    }
  },
  components: {
    Child
  },
  methods: {
    openDialog () {
      this.$refs.child.visible = true
    },
    getSelected (value) {
      this.text = '选中了选项' + value
    }
  }
}
var Ctor = Vue.extend(Parent)
new Ctor().$mount('#parent')