vue中的组件是独立的个体,这意味着子组件不能直接引用父组件的数据。要让子组件使用父组件的数据,需要通过子组件的 props 选项。
父子组件之间的数据交换可参考下图:
image.png
使用props传递数据,分动态跟静态两种:
静态
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js" ></script>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
</body>
<script>
var childComponent = {
//子组件要显式地用 props 选项声明它期待获得的数据
props:['parentMsg'],
//静态Prop通过子组件在父组件中的占位符添加特性的方式来达到传值的目的
template: '<h3>child get message:{{parentMsg}}</h3>'
}
var parentComponent = {
template: "<h1>this is parent. <child-component parentMsg='nice to meet you !'></child-component> </h1>",
components: {
'child-component':childComponent
}
};
// 创建根实例
new Vue({
el: '#app',
components: {
'parent-component': parentComponent
}
})
</script>
</html>
动态
我们可以通过v-bind的方式,将父组件的data传递给子组件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" />
<my-component v-bind:message="message"></my-component>
</div>
</body>
<script>
var MyComponent = Vue.extend({
props: ['message'],
template: "<p>{{ 'From parent : ' + message }}</p>"
})
Vue.component('my-component', MyComponent);
var vm = new Vue({
el: '#app',
data: {
message: 'default'
}
});
</script>
</html>
image.png
绑定类型
双向绑定 .sync,单次绑定 .once
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<div>
Parent component:<input type="text" v-model="msg" />
</div>
<my-bind :msg.sync="msg"></my-bind>
</div>
</body>
<script>
Vue.component('my-bind', {
props: ['msg'],
template: '<div>Child component :<input type="text" v-model="msg" /></div>'
});
var vm = new Vue({
el: '#app',
data: {
msg: ''
}
});
</script>
</html>













网友评论