The company's projects, except for the ones I created, are mostly Vue2 projects. It is well known that the original Vue2 plugin, Vetur, needs to enable the "vetur.experimental.templateInterpolationService"
option to provide code completion in templates. Adding @vue/composition-api
can also be used, but adding unplugin-vue2-script-setup
to solve the problem of too many variables returned by using composition-api is not very effective, so something needs to be introduced to enhance the development experience in this environment.
Using composition-api in Vue2#
Before Vue3 was officially released, @vue/composition-api
was already available to support the use of composition API in Vue2.
You can use it according to the configuration provided in the documentation.
Adding support for Vue2's setup syntax sugar#
unplugin-vue2-script-setup is a plugin developed by Vue team core member Anthony Fu based on his own development of compatibility tools for Rollup and webpack plugins. It allows Vue2 projects to use the setup syntax sugar and even the ref syntax sugar. You can check the repository for specific usage methods.
However, after using this plugin, the prompt function of Vetur is basically disabled and it will prompt that there is no default export. The development experience is not very good. Next, let's introduce Volar recommended by Vue3.
Using Volar#
Although it is a plugin dedicated to Vue3, it also supports Vue2 without any problems.
First, Volar uses @vue/runtime-dom
to obtain type checking for Vue files, but this package is not available in Vue2, so we need to install it manually.
npm install -D @vue/runtime-dom
Then, add the following two settings to the jsconfig.json file of the project.
{
"compilerOptions": {
"types": ["unplugin-vue2-script-setup/types"],
},
"vueCompilerOptions": {
"experimentalCompatMode": 2
}
}
Turn off Vetur and enable Volar, then wait for the Vue language server to start. You should be able to enjoy a better development experience when opening Vue files.
A small drawback#
For components imported using the setup syntax sugar, Volar cannot properly colorize and provide type completion for them. Therefore, I suggest separating the naming of components and the import of child components into another script block, like this:
<script>
import { defineComponent } from '@vue/composition-api'
import HelloWorld from './components/HelloWorld.vue'
export default defineComponent({
name: 'App',
components: { HelloWorld },
})
</script>
<script setup>
import { ref } from '@vue/composition-api'
const count = ref(0)
const countAdd = () => {
count.value++
}
</script>
Since we need to name the components anyway, it can also solve this small problem. Let's do it this way.