父子組件間傳值

環境說明: vue-cli(vue 3.x) + ant-vuehtml

父組件(Album.vue)使用: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):vue-cli

<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須要綁定的是一個雙向數據流的變量!

less

相關文章
相關標籤/搜索