在 Vue 中,子组件默认是无法访问父组件中的值的。
要实现子组件可以访问父组件中的数据,父组件可以在引用子组件的时候,通过属性绑定的形式把需要传递给子组件的数据以属性绑定的形式传递到子组件使用 。
<body>
<div id="app">
<com1 v-bind:parentmsg="msg"></com1>
</div>
</body>
<script type="text/javascript">
var vm = new Vue({
el : '#app',
data:{
msg: ''
},
components: {
com1:{
template: '{{parentmsg}}',
props: ['parentmsg']
}
}
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Vue父组件向子组件传值</title>
<script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script>
</head>
<body>
<div id="app">
<!-- 父组件可以在引用子组件的时候,可以通过属性绑定的形式把需要传递给子组件的数据以属性绑定的形式传递到子组件使用 -->
<com1 v-bind:parentmsg="msg"></com1>
<p>嗨客网(www.haicoder.net)</p>
</div>
</body>
<script type="text/javascript">
var vm = new Vue({
el : '#app',
data:{
msg: '这是父组件中的数据'
},
components: {
//子组件默认是无法访问父组件 data 上的数据和方法的
com1:{
data(){ //子组件中的data数据,并不是通过父组件传递过来的,而是子组件自身私有的
return {
}
},
template: '<h1>这是子组件--{{parentmsg}}</h1>',
// 组件中的所有的 props中的数据,都是通过 父组件传递给子组件的
// props 中的数据都是制度的,无法重新赋值
props: ['parentmsg'] //把父组件传递过来的 parentmsg 属性,先在 props数组中先定义一下,这样才可以使用这个数据
}
}
});
</script>
</html>
浏览器运行效果,如下图所示:
我们在父组件中,引用子组件 com1 的时候,通过属性绑定的形式将父组件的 msg 数据传递以 key 为 parentmsg 的形式传递给子组件。
接着,我们在子组件的属性 props 数组中,引用父组件传递过来的数据。接下来,我们就可以在子组件的 template 中引用父组件的数据了。
在 Vue 中,要实现子组件可以访问父组件中的数据,父组件可以在引用子组件的时候,通过属性绑定的形式把需要传递给子组件的数据以属性绑定的形式传递到子组件使用 。