Vue.js 使用props传递数据

2019-08-15  本文已影响0人  Rinaloving
基本用法

组件不仅仅是要把模板的内容进行复用,更重要的是组件间要进行通信。通常父组件的模板中包含子组件,父组件要正向地向子组件传递数据或参数,子组件接收到后根据参数的不同来渲染不同的内容或执行操作。这个正向传递数据的过程就是通过props来实现的。
在组件中,使用选项props来声明需要从父级接收的数据,props的值可以是两种,一种是字符串数组,一种是对象。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>使用props传递数据</title>
</head>
<body>
    <!--自动识别最新稳定版本的Vue.js-->
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

    <div id="app">
        <my-component message="来自父组件的数据"></my-component>
    </div>

    <script>
        Vue.component(
            'my-component',{
            props:['message'],
            template:'<div>{{ message }}</div>'
        });

        var app = new Vue({
            el:'#app'
        })
    </script>

</body>
</html>
使用props传递数据.png

props 中声明的数组与组件data函数return的数据主要区别就是props的来自父级,而data中的是组件自己的数据,作用域是组件本身,这两种数据都可以在模板template及计算属性computed和方法method中使用。上例的数据message就是通过props从父级传递过来的,在组件的自定义标签上直接写该props的名称,如果要传递多个数据,在props数组中添加即可。

  <div id="app2">
        <my-component warning-text="提示信息"></my-component>
    </div>

    <script>
        Vue.component('my-component',{
            props:['warningText'],
            template:'<div>{{ warningText }}</div>'
        });

        var app = new Vue({
            el:'#app2'
        })

    </script>

使用props传递多个数据.png

有时候,传递的数据并不是直接写死的,而是来自父级的动态数据,这时可以使用指令v-bind来动态绑定props的值,当父组件的数据变化时,也会传递给子组件。示例:

   <div id="app3">
        <input type="text" v-model="parentMessage">
        <my-component :message="parentMessage"></my-component>
    </div>

    <script>
        Vue.component('my-component',{
            props:['message'],
            template:'<div>{{ message }}</div>'
        });

        var app = new Vue({
            el:'#app3',
            data:{
                parentMessage:''
            }
        })

    </script>

动态传递.png

这里用 v-model 绑定了父级的数据 parentMessage ,当通过输入框输入时,子组件接收到的props “message ” 也会实时响应,并更新组件模板。

注意

如果你要直接传递数字、布尔值、数组、对象,而且不使用v-bind,传递的仅仅是字符串,尝试下面示例:

    <div id="app4">
        <my-component message="[1,2,3]"></my-component>
        <my-component :message="[1,2,3]"></my-component>
    </div>

    <script>
        Vue.component('my-component',{
            props:['message'],
            template:'<div>{{ message.length}}</div>'
        });

        var app = new Vue({
            el:'#app4'
        })

    </script>

同一个组件使用了两次,区别仅仅是第二个使用的是 v-bind。渲染后的结果,第一个是7,第二个才是数组的长度3。

传递数字.png
上一篇 下一篇

猜你喜欢

热点阅读