vue二十一:vue基础之ref实现父子通信

ref存在于vue实例中

ref放在标签上,拿到的是原生节点

获取vue实例下,ref中,inputText输入框的值

ref放在组件上,拿到的是组件对象

访问子组件的状态和方法(子传父)

父传子

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" ref="inputText">
<button @click="handleAdd">add</button>
<child ref="mychild"></child>

</div>

<script>
// 子组件
Vue.component('child', {
template: `
<div>
child
</div>
`,
data() {
return {
childname: '子组件的状态'
}
},
methods: {
add(msg) {
console.log('子组件的方法', msg)
}
}
})

new Vue({
el: "#app",
methods: {
handleAdd() {
// console.log(this.$refs.inputText.value)

// console.log(this.$refs.mychild.childname) // 子组件的状态
// this.$refs.mychild.add() // 子组件的方法

this.$refs.mychild.childname = 'aaaa'
console.log(this.$refs.mychild.childname) // 子组件的状态
this.$refs.mychild.add('这是父组件传给子组件的信息') // 子组件的方法
}
}
})

</script>
</body>
</html>
讨论群:249728408
原文地址:https://www.cnblogs.com/zhongyehai/p/12383793.html