Vue:原生DOM元素的获取

Vue获取标签的方式(ref)

1、给标签或组件添加 ref 属性,在mounted()方法中,通过$.refs获取

<div ref="alex"></div>
<p ref="a"></p>
<Home ref="b"></Home>


this.$refs.alex    获取原始的DOM对象
this.$refs.a
this.$refs.b       获取组件实例化对象

2、举例

<div id="app">

</div>

<script src="../vue.js"></script>
<script>
    Vue.component('Test', {
        data() {
            return {}
        },
        template: `
            <div>我是test</div>
            `,
    });

    let App = {

        data() {
            return {}
        },
        template: `
            <div>
                <input type="text" ref = 'input'>
                <Test ref = 'abc'></Test>
            </div>
            `,
        mounted() {
       //DOM渲染之后调用 console.log(
this.$refs.input);//获取原始DOM this.$refs.input.focus(); //设置焦点
console.log(
this.$refs.abc); //获取组件实例对象
console.log(this.$refs.abc.$parent); //获取父组件
console.log(this.$refs.abc.$root);//获取根vue实例
console.log(this.$children[0
]); //子组件的第一个,根据template中加载子组件的顺序排序 } }; let vm = new Vue({ el: '#app', data() { return {} }, template: `<App></App>`, components: { App } }) </script>

 

posted @ 2018-12-02 23:48  葡萄想柠檬  Views(2660)  Comments(0)    收藏  举报
目录代码