Vue 之子组件向父组件通信

8次阅读

共计 603 个字符,预计需要花费 2 分钟才能阅读完成。

如何把子组件内特定的数据传给父组件?
例如把子组件的名字传给父组件并在父组件上显示
思路在子组件被点击后 emit 一个事件名和组件的名字在父组件上监听子组件 emit 出的事件,并触发处理函数这个处理函数将子组件传出的子组件名字显示在父组件上
<!DOCTYPE html>
<html lang=”en” dir=”ltr”>
<head>
<meta charset=”utf-8″>
<title></title>
<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js”></script>
</head>
<body>
<div id=”app”>
child name: {{child}}
<child v-on:say=’greeting(“child”, $event)’></child>
</div>
</body>
<script>
Vue.component(‘child’, {
template: `
<div>
child
<button v-on:click=’$emit(“say”, “Jack”)’>greeting</button>
</div>
`
})
new Vue({
el: ‘#app’,
data: {
child: ”,
},
methods: {
greeting: function (key, value) {
this[key] = value
},
}
})
</script>
</html>

正文完
 0