父组件传递数据给子组件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>父组件传值给子组件</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<father v-bind:fatherinfo="vueinfo"></father>
</div>
<script>
Vue.component('father', {
props: ['fatherinfo'],
components: {
'inner': {
props: ['innerinfo'],
template: '<p>I am inner,info:{{ innerinfo }}</p>'
}
},
template: `
<div>
<p>I am father,info:{{ fatherinfo }}</p>
<inner v-bind:innerinfo="fatherinfo"></inner>
</div>
`
})
let vm = new Vue({
el: '#app',
data: {
vueinfo: 'I am vue info'
}
})
</script>
</body>
</html>
效果:
在上面的例子中,父组件 father 组件将从 Vue 实例获取的 vueinfo 传递给了子组件 inner。
fater 组件首先通过 v-bind 指令获取到 Vue 实例的 vueinfo,并将其赋值给自定义属性 fatherinfo,然后再通过 v-bind 指令将该值赋值给子组件 inner 的自定义属性 innerinfo,从而实现了父组件传值给子组件。
子组件 v-bind 的值查询范围仅限于直接父组件,在上面的例子中:
inner 组件 v-bind 的值查询范围仅限于父组件 father 组件,它不能通过 v-bind 指令直接访问到 Vue 实例的数据。
如果 inner 组件内部又定义了子组件,那这个新定义的子组件 v-bind 指令只能查询到 inner 组件的数据,不能直接查询到 father 组件的数据。
子组件传递数据给父组件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>子组件传值给父组件</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<father v-bind:fatherinfo="info"></father>
</div>
<script>
Vue.component('father', {
props: ['fatherinfo'],
components: {
'inner': {
template: `
<div>
<button v-on:click="$emit('changeinfo', 'innerinfo')">change</button>
<p>点击按钮之后,fatherinfo 的值将变为 innerinfo</p>
</div>
`
}
},
methods: {
change: function(e) {
this.fatherinfo = e;
}
},
template: `
<div>
<p>fatherinfo: {{ fatherinfo }}</p>
<inner v-on:changeinfo="change"></inner>
</div>
`
});
let vm = new Vue({
el: '#app',
data: {
info: 'I am vue info'
}
})
</script>
</body>
</html>
效果:
在上面的例子中,子组件 inner 通过 $emit 改变了 父组件 father 组件的自定义属性 fatherinfo 的值,这种操作会让 Vue 在浏览器的控制台中发出警告 QAQ。
$emit 方法会触发当前实例上事件,此方法第一个参数为事件名,第二个参数是一个参数数组,会传给监听器回调,在上面的例子中:
子组件 inner 通过 $emit 方法触发 changeinfo 事件,这个事件被监听到后又触发了 change 函数,在 change 里面,$emit 方法的第二个参数会被传入,从而修改父组件 father 组件的自定义属性 fatherinfo 的值。