// 子组件向父组件传值 emit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div id="counter-event-example">
<button-counter @increment="incrementTotal"></button-counter> //@子组件需要emit的内容="父组件执行的时间"
</div>
</div>
<script>
//子组件
Vue.component('button-counter', {
template: '<button @click="increment1">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment1: function () {
this.$emit('increment',2)//子组件emit出对应内容,传递一个参数2
}
},
})
//父组件
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (temp) {//父组件接收到emit消息,拿到temp参数2,并执行这个函数。
this.total += temp
}
}
})
</script>
</body>
</html>
总结:子组件利用点击事件increment1触发,emit出事件increment,可以传递值2。父组件接到emit,并拿到传递来的值,执行对应事件incrementTotal。实现了从子组件到父组件的传递。
//父组件向子组件传值 prop
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
//父组件传值hello,子组件定义好message接收
<child message="hello!"></child>
</div>
<script>
// 子组件注册
Vue.component('child', {
// 声明 props接收
props: ['message'],
// 就可以“this.message” 这样使用
template: '<span>{{ message }}</span>'
})
// 创建根实例
new Vue({
el: '#app'
})
</script>
</body>
</html>
总结,父组件 :子组件变量=父组件变量, 子组件中props:[子组件变量]就可以使用了