A brief discussion on the alternative method of $refs in vue2 in vue3 combined API

A brief discussion on the alternative method of $refs in vue2 in vue3 combined API

If you have experience in vue2 project development, you will be familiar with $refs. Due to the cliff-like upgrade of vue3, how to use $refs in vue3? I guess you have encountered similar problems before. I have the same doubts. Through search engines and GitHub, you can basically master how to use $refs. In vue3, use the function ref of the combined API to replace the application of static or dynamic html elements.

Recently, I have been learning the development of the vue3 project "Crayon Management Template: Vue3 + Vuex4 + Ant Design2" in my spare time. The iteration has been advanced a little in the past two days, and the chart component has been implemented. When I was writing the article, I found that there was a typo in the commit of the submitted code.

When using the setup() method of the combined API in vue3, this.$refs cannot be used normally, but the new function ref() can be used.

The following code is taken from: https://github.com/QuintionTang/crayon/blob/feat-dashboard/src/qtui/components/Chart.vue

<template>
    <canvas ref="refChart" :height="setHeight"></canvas>
</template>
<script>
import { defineComponent, onMounted, ref, inject, watch } from "vue";
import Chart from "chart.js";
import { deepCopy } from "@/helper/index";
export default defineComponent({
    name: "QtChart",
    props: {
        type: {
            type: String,
            required: true,
            default: "line",
        },
        data: {
            type: Object,
            required: true,
            default: () => ({}),
        },
        options:
            type: Object,
            default: () => ({}),
        },
        height:
            type: Number,
            default: 0,
        },
        refKey: {
            type: String,
            default: null,
        },
    },
    setup(props) {
        const refChart = ref();
        // Initialization method const init = () => {
            const canvasChart = refChart.value?.getContext("2d");
            const chartHelper = new Chart(canvasChart, {
                type: props.type,
                data: deepCopy(props.data),
                options: props.options,
            });
            watch(props, () => {
                chartHelper.data = deepCopy(props.data);
                chartHelper.options = props.options;
                chartHelper.update();
            });
            // Attach an instance to refChart
            refChart.value.instance = chartHelper;
        };
        // Set the height const setHeight = () => {
            return {
                height: props.height,
            };
        };
        // Bind an instance and use inject const bindInstance = () => {
            if (props.refKey) {
                const bind = inject(`bind[${props.refKey}]`);
                if (bind) {
                    bind(refChart.value);
                }
            }
        };
        onMounted(() => {
            bindInstance();
            init();
        });
        return {
            refChart,
            setHeight,
        };
    },
});
</script>

This code fully implements a chart component Chart, in which the property props is customized and its property value is used by passing parameters to the setup method. Define a ref="refChart" in html as the dom object of the chart. In the setup method, use the ref method to define a responsive variable object and use it as the return value at the end of the setup function.

const refChart = ref();

It should be noted that the attribute name of the return value must be consistent with the ref value in the HTML.

The following code can be executed normally.

<template>
    <canvas ref="refChart" :height="setHeight"></canvas>
</template>
<script>
import { defineComponent, onMounted, ref, inject, watch } from "vue";
import Chart from "chart.js";
import { deepCopy } from "@/helper/index";
export default defineComponent({
    name: "QtChart",
    props: {
        // ... 
    },
    setup(props) {
        const refChartBox = ref();
        // ...
        return {
            refChart:refChartBox,
        };
    },
});
</script>

In the following situations, program errors will occur and the expected results cannot be achieved. This is because the ref="refChart" defined in the html is inconsistent with the refChartBox returned by setup.

<template>
    <canvas ref="refChart" :height="setHeight"></canvas>
</template>
<script>
import { defineComponent, onMounted, ref, inject, watch } from "vue";
import Chart from "chart.js";
import { deepCopy } from "@/helper/index";
export default defineComponent({
    name: "QtChart",
    props: {
        // ... 
    },
    setup(props) {
        const refChartBox = ref();
        // ...
        return {
            refChartBox,
        };
    },
});
</script>

in conclusion

This article only briefly introduces the use of the ref method, which happens to be used in the project. In the future, I will continue to learn while advancing the project and taking notes.

This is the end of this article about the alternative method of $refs in vue2 in vue3 combinatorial API. For more relevant vue3 combinatorial API content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue3+script setup+ts+Vite+Volar project
  • Vue3 based on script setup syntax $refs usage

<<:  How to block and prohibit web crawlers in Nginx server

>>:  How to move mysql5.7.19 data storage location in Centos7

Recommend

HTML introductory tutorial HTML tag symbols quickly mastered

Side note <br />If you know nothing about HT...

Detailed explanation of lazy loading and preloading of webpack

Table of contents Normal loading Lazy Loading Pre...

The image element img has extra blank space in IE6

When doing DIV+CSS layout of the page, it is very...

Vue implements a scroll bar style

At first, I wanted to modify the browser scroll b...

How to install theano and keras on ubuntu system

Note: The system is Ubuntu 14.04LTS, a 32-bit ope...

Detailed explanation of non-parent-child component value transfer in Vue3

Table of contents App.vue sub1.vue sub2.vue Summa...

Specific usage of Vue's new toy VueUse

Table of contents Preface What is VueUse Easy to ...

Creating Responsive Emails with Vue.js and MJML

MJML is a modern email tool that enables develope...

Detailed graphic explanation of MySql5.7.18 character set configuration

Background: A long time ago (2017.6.5, the articl...

The vue project realizes drawing a watermark in a certain area

This article shares with you how to use Vue to dr...

Detailed installation and configuration tutorial of MySQL 5.7 under Win10

1. Unzip MySQL 5.7 2. Create a new configuration ...

How to find and delete duplicate rows in MySQL

Table of contents 1. How to find duplicate rows 2...