ref 本身是作为渲染结果被创建的
在初始渲染的时候你不能访问它们 - 它们还不存在!$refs
也不是响应式的,因此不应该试图用它在模板中做数据绑定。
ref 的基本使用,用在元素上:
- DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>title>
- <script src="js/vue.js" type="text/javascript" charset="utf-8">script>
- head>
- <body>
- <div id="app">
- <div ref="aa" id="aa">
- 我们在学习vue
- div>
- <button type="button" @click="getdom">点击button>
- div>
- <script>
- const vm = new Vue({
- el:'#app',
- data(){
- return {
-
- }
- },
- methods:{
- getdom(){
- let a = document.getElementById('aa')
- console.log(a);
- console.log(this.$refs.aa);
- }
- }
-
-
- })
- script>
- body>
- html>
$refs方式:ref
被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs
对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件
ref可以调用组件中的方法:
- DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>title>
- <script src="js/vue.js" type="text/javascript" charset="utf-8">script>
- head>
- <body>
- <div id="app">
- <hello-world ref="hello">hello-world>
- <button @click="getHello">获取helloworld组件中的值button>
- div>
-
- <template id="cpn">
- <div>111div>
- template>
- <script>
- //子组件
- const HelloWorld = {
- template: '#cpn',
- data() {
- return {
- number: 0
- }
- },
- methods: {
- handelclick() {
- console.log('被调用了');
- }
- }
- }
- //父组件
- const vm = new Vue({
- el: '#app',
- data() {
- return {
-
- }
- },
- components: {
- HelloWorld
- },
- methods: {
- getHello() {
- console.log(this.$refs.hello);
- console.log(this.$refs.hello.number);
- console.log(this.$refs.hello.$el.innerHTML);
- }
- }
-
- })
- script>
- body>
- html>
ref在子组件上的使用:
- DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>title>
- <script src="js/vue.js" type="text/javascript" charset="utf-8">script>
- head>
- <body>
- <div id="app">
- <counter @changenum="change" ref="num1">counter>
- <counter @changenum="change" ref="num2">counter>
- <h3>总价:{{total}}h3>
- div>
- <template id="cpn">
- <div @click="handelclick">{{number}}div>
- template>
- <script>
- const counter = {
- template:'#cpn',
- data(){
- return {
- number:0
- }
- },
- methods:{
- handelclick(){
- this.number++
- this.$emit('changenum')
- }
- }
- }
- const vm = new Vue({
- el:'#app',
- data(){
- return {
- total:0
- }
- },
- components:{
- counter
- },
- computed:{
- /* total(){
- console.log(this.$refs.num1);
- return this.$refs.num1.number +this.$refs.num2.number
- } */
- },
- methods:{
- change(){
- console.log(this.$refs);
- this.total = this.$refs.num1.number +this.$refs.num2.number
- }
- }
-
- })
-
- //总结:ref可以实现组件通讯 同时在computed中是无法获取this.$refs的
- script>
- body>
- html>