通过 Prop 向子组件传递数据
Prop
是你可以在组件上注册的一些自定义 attribute
。当一个值传递给一个 prop attribute
的时候,它就变成了那个组件实例的一个 property
。
//一个 prop 被注册之后,你就可以像这样把数据作为一个自定义 attribute 传递进来:
<blog-post title="My journey with Vue"></blog-post>
<blog-post title="Blogging with Vue"></blog-post>
<blog-post title="Why Vue is so fun"></blog-post>
<script>
Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})
</script>
一个组件默认可以拥有任意数量的 prop
,任何值都可以传递给任何 prop
。
demo
<!DOCTYPE html>
<html>
<head>
<title>Component Blog Post Example</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="blog-post-demo" class="demo">
<blog-post
v-for="post in posts"
:key='post.id'
:post='post'
></blog-post>
</div>
<script>
Vue.component("blog-post", {
props: ["post","content"],
// 折行转义字符 支持 IE
// template: "<div>\
// <h3>{{ post.title }}</h3><p>{{ post.body }}</p>\
// </div>"
// 模板字符串 不支持 IE
template:`<div>
<h3>{{ post.title }}</h3><p>{{ post.body }}</p>
</div>`
});
// 实例化vue
new Vue({
el: "#blog-post-demo",
data: {
posts: [
]
},
// 生命周期钩子 eated 这个钩子在实例被创建之后被调用
created: function() {
// Alias the component instance as `vm`, so that we
// can access it inside the promise function
var vm = this;
// Fetch our array of posts from an API
//fetch 在浏览器中直接提供其提供的api轻松与后台进行数据交互
fetch("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
//将其转化为json对象
return response.json();
})
.then(function(data) {
//将值赋值到vue的数据中
vm.posts = data;
});
}
});
</script>
</body>
</html>