父组件向子组件传值
利用 props 传值
// 静态传值
<body>
<div id="app">
<child msg='你好,子组件'></child>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component('child', {
props: ['msg'],
template: `
<h1>{{msg}}</h1>
`,
})
var vm = new Vue({
el: '#app'
})
</script>
</body>
// 动态传值,如果vm实例中的childMsg改变,那么子组件中显示的值也会发生改变
<body>
<div id="app">
<child :msg='childMsg'></child>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component('child', {
props: ['msg'],
template: `
<h1>{{msg}}</h1>
`,
})
var vm = new Vue({
data: {
childMsg: 'hi'
},
el: '#app'
})
</script>
</body>
子组件向父组件传值
子组件发送自定义事件,父组件接受事件
<body>
<div id="app">
// $event获取得到的参数
<child v-on:child-emit='handle($event)'></child>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component('child', {
template: `
<button v-on:click="$emit('child-emit', 'hello')">点击</button>
`,
})
var vm = new Vue({
data: {
childMsg: 'hi'
},
el: '#app',
methods: {
handle: function(data) {
console.log(data);
},
}
})
</script>
</body>
非父子组件之间的传值
利用事件中心注册事件, 组件触发事件
<body>
<div id="app">
<sister></sister>
<brother></brother>
</div>
<script src="./js/vue.js"></script>
<script>
// 创建事件中心
var middle = new Vue();
// 创建组件
Vue.component('sister', {
data: function() {
return {
num: 0
}
},
template: `
<button v-on:click='handle'>{{num}}</button>
`,
methods: {
handle: function() {
// 发送事件
middle.$emit('sister', 1);
}
},
mounted: function() {
// 创建事件并监听
middle.$on('brother', (val) => {
this.num += val;
});
}
});
Vue.component('brother', {
data: function() {
return {
num: 0
}
},
template: `
<button v-on:click='handle'>{{num}}</button>
`,
methods: {
handle: function() {
middle.$emit('brother', 2);
}
},
mounted: function() {
middle.$on('sister', (val) => {
this.num += val;
console.log(this);
});
}
});
var vm = new Vue({
el: '#app'
});
</script>
</body>