'How do I use the custom plugin in <script setup> in vue 3?
//TestPlugin.js
const randomValue = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
const random = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random);
};
export default {
install(Vue) {
Vue.config.globalProperties.$randomValue = randomValue;
},
};
//App.vue
<template>
<button>event</button>
</template>
This code is an example. I want to call the randomValue function within <script setup> and put it in a button instead of <buton@click="$randomValue(0, 20)">
The following is an example of what I want to do.
//App.vue
<template>
<button @click="random">event</button>
</template>
<script setup>
const random = $randomValue(0,10);
</script>
How do I do this?
Solution 1:[1]
I found the answer myself...
//TestPlugin.js
export default {
install(Vue) {
Vue.config.globalProperties.$randomValue = randomValue;
Vue.config.globalProperties.$valueCheck = valueCheck;
Vue.provide("plugins", { valueCheck, randomValue });
},
};
//App.vue
<script setup>
import { inject } from 'vue';
const { valueCheck, randomValue } = inject("plugins");
const hello = () => {
randomValue(0,10);
}
</script>
I added Vue.provide("plugins", { valueCheck, randomValue }); and import { inject } from 'vue'; const { valueCheck, randomValue } = inject("plugins");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Seona Sim |
