Vue组件通讯之父传子

组件是Vue中的重头戏,今天开始我会陆续分享自己在学习中的有关组件通讯的一些心得。

父组件传值子组件

<!DOCTYPE html>
<html lang="en">

<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>Aui车养护</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>

<body>
    <div id="app">
          <blog-post title="与青春有关的日子"></blog-post>
    </div>
    <script>
        Vue.component('blog-post', {
            // props: ['title'],
            props: {
                title: {
                    type: String,
                }
            },
            template: '<h3>{{ title }}</h3>'
        })
        let vm = new Vue({
            el: "#app",
            data: {
                blog: "我的青春谁做主",
            },
        });
    </script>
</body>

</html>

下面 对上面的程序做个解读:

1.首先定义了一个全局的组件名字为blog-post;

2.title="",传入的就是字符串(静态赋值),如果传入变量的时候title="blog"(动态赋值),此时需要v-bind指令;

3.父传子的重要属性是props属性,它有两种形式,一是数组的形式(不推荐),一是对象的形式。

4.props属性有三个重要的参数 type 、required和default;这些是可以传入的属性的类型props: { title: String, likes: Number, isPublished: Boolean, commentIds: Array, author: Object }。

猜你喜欢

转载自blog.csdn.net/qq_36818627/article/details/88577797