- ref被用來給元素或子元件註冊引用資訊。引用資訊將會註冊在父元件的
$refs
物件上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子元件上,引用就指向元件例項:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app">
<!-- 操作普通的 DOM 元素 -->
<button type="button" @click='clickA' class="btn btn-danger">button</button>
<h1 ref="h1">hello world</h1>
<!-- 操作元件 -->
<com ref="com">
<h1>click</h1>
</com>
</div>
<template id="comA"></template>
<script>
var vm = new Vue({
el: '#app',
data: {},
methods: {
clickA() {
//操作普通的 DOM 元素
console.log(this.$refs.h1.innerText)
//console.log(this.$refs.comA.msg)
//操作元件的data
console.log(this.$refs.com.msg)
//操作元件的methods
this.$refs.com.show()
}
},
components: {
'com': {
template: '#com',
data() {
return {
msg: 'msg'
}
},
methods: {
show() {
console.log('show')
}
},
}
}
});
Vue.config.devtools = true
</script>
</body>
</html>