zoukankan      html  css  js  c++  java
  • vue 使用ref获取DOM元素和组件引用

    在vue中可以通过ref获取dom元素,并操作它,还可以获取组件里面的数据和方法。

    HTML部分:

    1     <div id="app">
    2         <input type="text" value="input 的值" ref="myinput" />
    3         <h3 id="h3" ref="myh3">这是H3 </h3>
    4 
    5         <hr>
    6         <com1 ref="mycom1"></com1>
    7 
    8         <button @click="click">ref</button>
    9     </div>

    JS部分:

     1     // 定义一个组件
     2     var com1 = {
     3         template: `<div>这是子组件的内容</div>`,
     4         data() {
     5             return {
     6                 msg: "子组件的数据"
     7             }
     8         },
     9         methods: {
    10             fun1() {
    11                 console.log("子组件的fun1方法");
    12             }
    13         }
    14     }
    15 
    16     // vue实例
    17     var app = new Vue({
    18         el: "#app",
    19         // data() { return {} },
    20         methods: {
    21             click() {
    22                 console.log(this.$refs.myinput.value);
    23                 console.log(this.$refs.myh3.innerHTML);
    24                 console.log(this.$refs.mycom1.msg);
    25                 this.$refs.mycom1.fun1();
    26             }
    27         },
    28         components: {
    29             com1
    30         }
    31     });

    点击 ref 按钮,得到以下结果:

  • 相关阅读:
    django 如何重用app
    vim常用命令
    linux find grep
    linux su su-的区别
    linux定时任务crontab
    linux shell的单行多行注释
    python字符串的截取,查找
    gdb调试
    python字符转化
    python读写文件
  • 原文地址:https://www.cnblogs.com/chenzongyan/p/10306754.html
Copyright © 2011-2022 走看看