Vue 語法當中有一個 ref的參數,現在就就介紹一下使用方式,它的目的就是父節點,獲取子節點數據的一個手段
首先我們這里有一個父節點father.vue,在這里我們定義了一個子節點child.vue,並且由父節點定義一個ref為childDatas,父節點需要獲取子節點的值,就可以直接通過this.$refs.childDatas里面獲取,換句話說,這個childDatas其實就是等於child.vue里面的data()信息,包括里面的方法, 所以當按鈕點擊的時候,執行test()函數就會從child.vue里面的data()里面獲取message的參數,這里會打印333, 所以當你獲取一些data()里面沒有的參數,自然就會是undefine了
<template>
<div>
<!--測試效果的按鈕-->
<button @click="test()">Test Ref</button>
<!--子節點-->
<Children ref="childDatas"></Children>
</div>
</template>
<script>
import Child from './child.vue'
export default{
methods:{
test(){
var test = this.$refs.childDatas.message
console.log(test)
}
},
components:{
Children:Child
}
}
child.vue
<template>
<div>I am Children</div>
</template>
<script>
export default{
data(){
return{
message:'333'
}
}
}
</script>
