Vuejs can't access refs from component

后端 未结 7 1361
终归单人心
终归单人心 2020-12-17 07:45

I am trying to get the canvas element which is inside a template of a component, found great documentations for vuejs1 but not for vuejs2 where "ref" is the only w

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 08:28

    I also ran into this error. The way i fixed this issue was by getting the refs in the updated hook. See my example below.

    In my data object I have an empty array called 'products'.

    data() {
        return {
            products: []
        }
    }
    

    In the updated hook I check if any refs are found. If not then nothing will happen. Then when there are products found, the script will continue. Next time Vue will come into the updated hook again, your script won't be triggerd again because now the length of the products array is bigger than one (if any refs could be found of course).

    updated() {
        let products = this.$refs.products;
        if (!products || this.products.length > 0) return;
    
        this.products = products;
        // run your logic here
    }
    

提交回复
热议问题