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

How to use Docker to package and deploy images locally

First time using docker to package and deploy ima...

Discuss the application of mixin in Vue

Mixins provide a very flexible way to distribute ...

Advantages and disadvantages of Table layout and why it is not recommended

Disadvantages of Tables 1. Table takes up more byt...

Typora code block color matching and title serial number implementation code

Effect: The title has its own serial number, the ...

Steps to create a Vite project

Table of contents Preface What does yarn create d...

Comprehensive explanation of CocosCreator hot update

Table of contents Preface What is Hot Change Coco...

js uses Canvas to merge multiple pictures into one implementation code

Solution function mergeImgs(list) { const imgDom ...

HTML end tag issue and w3c standard

According to the principles of W3C, each start tag...

Introduction to the use and disabling of transparent huge pages in Linux

introduction As computing needs continue to grow,...

jQuery plugin to achieve carousel effect

A jQuery plugin every day - jQuery plugin to impl...

Getting Started Tutorial on Using TS (TypeScript) in Vue Project

Table of contents 1. Introducing Typescript 2. Co...