父组件
<template><div><button @click="dialog">dialog</button><!-- v-if="visible" --><Dialog:visible="visible"@close="visible = false":data="data"/></div></template><script>import Dialog from '@/components/Dialog'export default {components: {Dialog},data() {return {visible: false,data: []}},methods: {dialog() {this.visible = true// 给子组件传一些数据this.data = [{ id: 12, name: 'eamien', age: 2 },{ id: 14, name: 'nuomi', age: 0 }]}}}</script>
子组件
<template><div class="app-container"><el-dialogtitle="提示":visible.sync="visible"@close="close"center><span>需要注意的是内容是默认不居中的</span><spanslot="footer"class="dialog-footer"><el-button @click="close">取 消</el-button><el-buttontype="primary"@click="primary">确 定</el-button></span></el-dialog></div></template><script>export default {name: 'test-dialog',props: {visible: {type: Boolean,default: false,required: true},data: {type: Array,default: []}},data() {return {listQuery: {}}},watch: {visible() {if (!this.visible) {return}// 正常请求console.log(this.data)}},methods: {close() {// Initialize the data in the componentthis.listQuery = {}this.$emit('close')},primary() {this.close()}}}</script>
:::info .sync在vue2.0的时候取消, props的双向绑定需要自己实现 :::
1. 组件第一次已经在父组件内初始化过了, 所以要使用watch监听,在watch内发送请求.2. 如果你不想使用watch, 要使用正常的 created, 或者是 mounted 等钩子时可以去掉watch, 在父组件上使用 v-if="visible"3. 这在做组件初始化数据时非常有用, 例如: 编辑注: 使用watch, v-if 或者都不适用, 同样适用不同场景, 自行判断.
