vue.js实战——props单向数据流

Vue2.x通过props传递数据是单向的了,也就是父组件数据变化时会传递给子组件,但是反过来不行。

业务中会经常遇到两种需要改变prop的情况,

  一种是父组件传递初始值进来,子组件将它作为初始值保存起来,在自己的作用域下可以随意使用和修改。这种情况可以在组件data内再声明一个数据,引用父组件的prop,示例代码如下:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div >
        <my-component :init-count="1"></my-component>
    </div>
    <script>
        Vue.component('my-component',{
            props:['init-count'],
            template:'<div>{{count}}</div>',
            data:function(){
                return {
                    count:this.initCount
                }
            }
        })
        new Vue({
            el:'#app',
        })
    </script>
</body>
</html>

组件中声明了数据count,它在组件初始化时会获取来自父组件的initCount,之后就与之无关了,只用维护count,这样就可以避免直接操作initCount。

另一种情况就是prop作为需要被转变的原始值传入。这种情况用计算属性就可以了,示例如下:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div >
        <mynew-component :width="100"></mynew-component>
    </div>
    <script>
        Vue.component('mynew-component',{
            props:['width'],
            template:'<div :>组件内容</div>',
            computed:{
                style:function(){
                    return {
                        width:this.width+'px',
                        background:'lightgray',
                        textAlign:'center'
                    }
                }
            }
        })
        new Vue({
            el:'#app',
        })
    </script>
</body>
</html>

注意:

  在JavaScript中对象和数组是引用类型,指向同一个内存空间,所以props是对象和数组时,在子组件内改变是会影响父组件的。

  //如此解决引用传递

  1:var newObject = jQuery.extend(true, {}, oldObject);

 2:varobj={};

obj=JSON.parse(JSON.stringify(oldObject));