随笔- 372  评论- 80  文章- 0 

父子组件间传值

环境说明: vue-cli(vue 3.x) + ant-vue

父组件(Album.vue)使用:

<template>
  <div>
    <a-button type="primary" icon="plus" @click="uploadImage">图片</a-button>
    <upload-image :visible.sync="visible"></upload-image>
  </div>
</template>

<script>
import UploadImage from "./UploadImage";

export default {
  name: "Album",
  components: { UploadImage },
  data: function() {
    return {
      visible: false
    };
  },
  methods: {
    uploadImage() {
      this.visible = true;
    }
  }
};
</script>

<style scoped>
</style>

 子组件(UploadImage.vue):

<template>
  <a-modal
    :title="title"
    :visible="visible"
		@cancel="handleCancel"
		@ok="handleOk"
  >
		<h1>Some text here</h1>
  </a-modal>
</template>

<script>
export default {
	name: "UploadImage",
  props: {
    title: {
      type: String,
      default: "上传图片"
		},
		visible: {
			type: Boolean,
			default: false,
			required: true
		}
	},
	data: function() {
		return {
		}
	},
	methods: {
		handleCancel() {
			this.$emit('update:visible', false);
		},
		handleOk() {
			this.$emit('update:visible', false);
		}
	}
};
</script>

<style lang="less" scoped>
</style>

 综合:

1. 父组件使用时通过属性传递一个值到子组件, 并添加.sync修饰符

2. 子组件得到初始值后,若是修改了属性的值,通过this.$emit('update:xxx', newValue)修改父组件中绑定的变量值!

3. 注意子组件中v-model不能绑定一个属性, 因为属性是单向数据流,但是v-model需要绑定的是一个双向数据流的变量!

 

posted on 2019-08-31 15:27 清清飞扬 阅读(...) 评论(...) 编辑 收藏