vue2.X props 数据传递 实现组件内数据与组件外的数据的双向绑定

vue2.0 禁止 子组件修改父组件数据

在Vue2中组件的props的数据流动改为了只能单向流动,即只能由组件外(调用组件方)通过组件的DOM属性attribute传递props给组件内,组件内只能被动接收组件外传递过来的数据,并且在组件内,不能修改由外层传来的props数据

 

在Vue2.0中,实现组件属性的双向绑定方式

1. 在组件内的data对象中创建一个props属性的副本

 因为result不可写,所以需要在data中创建一个副本myResult变量,初始值为props属性result的值,同时在组件内所有需要调用props的地方调用这个data对象myResult

Vue.component("switchbtn", {
    template: "<div @click='change'>{{myResult?'开':'关'}}</div>",
    props: ["result"],
    data: function () {
        return {
            myResult: this.result//data中新增字段
        };
    },
    ......
});

 

2. 创建针对props属性的watch来同步组件外对props的修改

此时在组件外(父组件)修改了组件的props,会同步到组件内对应的props上,但是不会同步到你刚刚在data对象中创建的那个副本上,所以需要再创建一个针对props属性result的watch(监听),当props修改后对应data中的副本myResult也要同步数据。

Vue.component("switchbtn", {
    template: "<div @click='change'>{{myResult?'开':'关'}}</div>",
    props: ["result"],
    data: function () {
        return {
            myResult: this.result
        };
    },
    watch: {
        result(val) {
            this.myResult = val;//新增result的watch,监听变更并同步到myResult上
        }
    },
    ......

3. 创建针对props副本的watch,通知到组件外

此时在组件内修改了props的副本myResult,组件外不知道组件内的props状态,所以需要再创建一个针对props副本myResult,即对应data属性的watch
在组件内向外层(父组件)发送通知,通知组件内属性变更,然后由外层(父组件)自己来变更他的数据

最终全部代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="vue.js"></script>
</head>
<body>
	<div id="app">
   		<switchbtn :result="result" @on-result-change="onResultChange"></switchbtn>
   		<input type="button" value="change" @click="change">
	</div>

	<script> 
	    Vue.component("switchbtn", {
	        template: "<div @click='change'>{{myResult?'开':'关'}}</div>",
	        props: ["result"],
	        data: function () {
	            return {
	                myResult: this.result//第一步:建props属性result的副本--myResult
	            };
	        },
	        watch: {
	            result(val) {
	                this.myResult = val;//第二步:监听外部对props属性result的变更,并同步到组件内的data属性myResult中
	            },
	            myResult(val){
	                this.$emit("on-result-change",val);//第三步:组件内对myResult变更后向外部发送事件通知
	            }
	        },
	        methods: {
	            change() {
	                this.myResult = !this.myResult;
	            }
	        }
	    });

	    new Vue({
	        el: "#app",
	        data: {
	            result: true
	        },
	        methods: {
	            change() {
	                this.result = !this.result;
	            },
	            onResultChange(val){
	                this.result=val;//第四步:外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
	            }
	        }
	    });
	</script>
</body>
</html>

至此,实现了组件内数据与组件外的数据的双向绑定,组件内外数据的同步。最后归结为一句话就是:组件内部自己变了告诉外部,外部决定要不要变

.

原文地址:https://www.cnblogs.com/crazycode2/p/7616399.html