父组件

  1. <template>
  2. <div>
  3. <button @click="dialog">dialog</button>
  4. <!-- v-if="visible" -->
  5. <Dialog
  6. :visible="visible"
  7. @close="visible = false"
  8. :data="data"
  9. />
  10. </div>
  11. </template>
  12. <script>
  13. import Dialog from '@/components/Dialog'
  14. export default {
  15. components: {
  16. Dialog
  17. },
  18. data() {
  19. return {
  20. visible: false,
  21. data: []
  22. }
  23. },
  24. methods: {
  25. dialog() {
  26. this.visible = true
  27. // 给子组件传一些数据
  28. this.data = [
  29. { id: 12, name: 'eamien', age: 2 },
  30. { id: 14, name: 'nuomi', age: 0 }
  31. ]
  32. }
  33. }
  34. }
  35. </script>

子组件

  1. <template>
  2. <div class="app-container">
  3. <el-dialog
  4. title="提示"
  5. :visible.sync="visible"
  6. @close="close"
  7. center
  8. >
  9. <span>需要注意的是内容是默认不居中的</span>
  10. <span
  11. slot="footer"
  12. class="dialog-footer"
  13. >
  14. <el-button @click="close">取 消</el-button>
  15. <el-button
  16. type="primary"
  17. @click="primary"
  18. >确 定</el-button>
  19. </span>
  20. </el-dialog>
  21. </div>
  22. </template>
  23. <script>
  24. export default {
  25. name: 'test-dialog',
  26. props: {
  27. visible: {
  28. type: Boolean,
  29. default: false,
  30. required: true
  31. },
  32. data: {
  33. type: Array,
  34. default: []
  35. }
  36. },
  37. data() {
  38. return {
  39. listQuery: {}
  40. }
  41. },
  42. watch: {
  43. visible() {
  44. if (!this.visible) {
  45. return
  46. }
  47. // 正常请求
  48. console.log(this.data)
  49. }
  50. },
  51. methods: {
  52. close() {
  53. // Initialize the data in the component
  54. this.listQuery = {}
  55. this.$emit('close')
  56. },
  57. primary() {
  58. this.close()
  59. }
  60. }
  61. }
  62. </script>

:::info .sync在vue2.0的时候取消, props的双向绑定需要自己实现 :::

  1. 1. 组件第一次已经在父组件内初始化过了, 所以要使用watch监听,在watch内发送请求.
  2. 2. 如果你不想使用watch, 要使用正常的 created, 或者是 mounted 等钩子时
  3. 可以去掉watch, 在父组件上使用 v-if="visible"
  4. 3. 这在做组件初始化数据时非常有用, 例如: 编辑
  5. 注: 使用watch, v-if 或者都不适用, 同样适用不同场景, 自行判断.