search

Home  >  Q&A  >  body text

javascript - How to use $refs in vue2.0

How to use $refs in vue2.0? Please give a small example, thank you!

曾经蜡笔没有小新曾经蜡笔没有小新2794 days ago501

reply all(2)I'll reply

  • 迷茫

    迷茫2017-05-19 10:20:26

    <p id="parent">
      <user-profile ref="profile"></user-profile>
    </p>
    var parent = new Vue({ el: '#parent' })
    // 访问子组件
    var child = parent.$refs.profile

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:20:26

    For example, I used ueditor to make an Editor component
    Then there is a form on another page, which introduces the Editor. Of course, it is necessary to register in components!
    I click submit on the page, then the editor’s getContent() method will be used. So the question is, how to define the object where the getContent method is located? Or there are several components on a page, all of which have the getContent method. What should I do?
    The editor is given a ref attribute here, which I understand to be similar to the id in HTML.
    Then, using $refs in components or instances is to find all components with ref attributes! Then put it in an object.
    The key of the object is the attribute value of ref.

    <template>
        <p>
            <Editor ref="details"></Editor>
            <Table ref="mainTable"></Table>
            <Form ></Form>
        </p>
    </template>
    <script>
    export default (){
        data(){
            return {}
        },
        components:{Editor,Table,Form},
        methods:{
        getContent(){
                console.log(this.$refs);//这里打印的就是一系列的带有ref属性的组件构成的对象
                this.$refs.details.getContent();//这里就可以使用editor的getContent方法了
            }
        }
    }
    </script>

    reply
    0
  • Cancelreply