vue组件props双向绑定

在vue2中不允许子组件直接修改props,为单项数据流,所有若要修改只能通过额外的值,并监听props以改变额外的值。

设置props

1
2
3
4
5
6
props: {
    dialog: {
      type: Boolean,
      default: false
    }
}

创建额外的值

data中创建一个localDialog,其值为this.dialog

1
2
3
4
5
data() {
    return {
    	localDialog: this.dialog
    }
}

监听

保持同步的关键在于需要在子组件内监听props,即此处的dialog

1
2
3
4
5
watch: {
    dialog(val) {
      this.localDialog = val
    }
}

子组件向父组件传递

子组件使用this.$emit()即可向父组件传递变化的值。

1
2
3
4
5
methods: {
    sendToFather() {
        this.$emit('dialogchange', this.localDialog)
    }
}

父组件调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<your-component :dialog="dialog" @dialogchange="dialogchange" />
data() {
	return {
        dialog: false
    }
},
methods: {
    dialogchange(val) {
    	this.dialog = val
    }
}

完整代码

子组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
    <div :visible="localDialog">
        hunterji.com
		<button @click="sendToFather" />
    </div>
</template>

<script>
export default {
	props: {
    	dialog: {
      	type: Boolean,
      	default: false
    	}
	},
	data() {
        return {
            localDialog: this.dialog
        }
    },
    watch: {
   		dialog(val) {
      		this.localDialog = val
    	}
	},
    methods: {
    	sendToFather() {
        	this.$emit('dialogchange', this.localDialog)
    	}
	}
}
</script>

父组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
    <your-component :dialog="dialog" @dialogchange="dialogchange" />
</template>

<script>
import yourComponent from './yourComponent'

export default {
	components: {
        yourComponent
    },
    data() {
		return {
        	dialog: false
    	}
	},
	methods: {
    	dialogchange(val) {
    		this.dialog = val
    	}
	}
}
</script>
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy