Creating a Component and Programmatically Returning a Value in Vue.js: A Step-by-Step Guide

Could you assist me in solving my issue? I am looking to develop a customized plugin for my project so that my team and I can easily implement an alert component without having to design the dialog box repeatedly on every page and vuejs file.

My objective is to create an alert component plugin where we do not need to initialize the component in our vuejs files. For example, just by calling:

customise_alert.fire({ title: 'Confirmation message'})
.then((result) => {
  if(result.value == 1) console.log("option 1 is pressed")
});

I have tried various approaches but this is the closest I have come to achieving my goal.

Note: I am using Laravel with vuejs.

This is what my code looks like so far: PopUpComponent.vue

<template>
  <div>
    <v-dialog v-model="dialog_confirmation" max-width="400" content-class="c8-page">
      <v-card>
        <v-card-title class="headline">
          <v-icon v-show="icon_show" :color="icon_color">{{ icon }}</v-icon> {{ title }}
          <a href="#" class="dialog-close" @click.prevent="dialog_confirmation = false"><v-icon>mdi-close</v-icon></a>
        </v-card-title>
        <v-card-text>
          <div style="margin:10px;" v-html="message"></div>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn color="primary" depressed tile small @click="updateValue(1)">Yes</v-btn>
          <v-btn color="primary" depressed tile small @click="updateValue(2)">No</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>
<script>
export default {
  name: 'Cirrus-Alert-Confirmation',
  props: {
    title: {default: ''},
    message: {default: ''},
    icon_color: {default: 'while'},
    icon: {default: 'warning'},
    icon_show: {default: false}
  },
  data() {
    return {
      dialog_confirmation: false
    }
  },
  mounted() {

  },
  methods: {
    fire: function() {
      this.dialog_confirmation = true;
    },
    updateValue: function(value) {
      this.$emit('input', value);
      this.dialog_confirmation = false;
    }
  },
  watch: {

  },
}
</script>

global.js

import Vue from 'vue'
import PopUpComponent from "../components/elements/PopUpComponent";
Vue.prototype.$filters = Vue.options.filters;
var cirrus_alert = Vue.extend(CirrusPopUpComponent);
Vue.prototype.$alert = cirrus_alert;

main.js

import '../../plugins/global';
import Vue from 'vue'
import FormTemplate from '../../components/modules/Templates/FormTemplate.vue';
new Vue({
    el: '#app',
    SuiVue,
    vuetify,
    store,
    components : {
        'main-template-component' : FormTemplate,
    }
}).$mount('#app')

home.blade.php - short version (w/o the other declarations)

<main-template-component></main-template-component>

FormTemplate.vue (the function which triggers the alert)

let alert = new this.$alert({
   propsData:  { title: 'Sample' }
});
alert.$mount();
alert.fire({ title: 'Confirmation message'})
.then((result) => {
  if(result.value == 1) console.log("option 1 is pressed")
});

Thank you very much in advance.

Answer №1

Utilizing Vue mixins may provide a solution to your current issue. According to the documentation:

Mixins offer a versatile approach to sharing reusable functionalities among Vue components. A mixin object can encompass any component options. When a component incorporates a mixin, all of the mixin's options will be integrated into the component's own options.

You can establish a mixin directory and store your reusable files inside it, such as an alert, then import it wherever needed like demonstrated below :

<script>
import alert from '../../mixins/alert'

export default {
  name: 'Component1',
  mixins: [alert],
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying the value of a jquery variable in an HTML document

I'm tackling a problem differently today compared to yesterday, but my knowledge of jQuery and JavaScript is quite basic. My goal is to increment the transform value of a div every 5 seconds: <div style="transform: translateX(0px);" id="slide_ima ...

Tips for navigating upwards to a specific element and successfully clicking on it in Selenium

I am facing a situation where the system needs to scroll upwards to reach the web element located in the left panel of the page and then click on it to proceed with other operations. I have attempted various methods but none seem to be effective. Can anyon ...

What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary. Situation To save a post in the database, I can fill in just the title field initially and leave the other fiel ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

How can I append an object key to the end of a URL link within an anchor tag

I seem to be facing a problem where I am attempting to append the key of my object at the end of a URL. It appears to work fine as a button, but for some reason the key is not being displayed within the href attribute. Typically, I would use "+" to conca ...

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

Obtaining a URL in JavaScript

Hey there, I'm diving into the world of JavaScript and could use some guidance. I'm currently working on implementing forward and backward buttons on a webpage. The URL structure is http://webaddress.com/details?id=27 My goal is to write two fun ...

There was an error in the syntax: a semicolon is missing before the statement

During an ajax request, I encountered this error and upon reviewing it thoroughly, I am unable to pinpoint the cause. The following code snippet is where the issue seems to lie: $('#post_submit').click(function() { var poster_id = <?php echo ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Create-react-app unable to activate Service Worker

I've been utilizing the power of create-react-app to create my react.js project. Whenever I use the command npm run build, it automatically integrates a service-worker for progressive web app functionality in the production build. Everything was runn ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below: <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> ...

Issue with JQuery .fadeToggle() function: Unexpected behavior causing automatic fade-out

$(document).on('click', '.tree label', function(e) { $(this).next('ul').fadeToggle(); e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul cl ...

Tips for steering clear of global variables while coding in JavaScript

What is the best way to avoid using global variables in JavaScript? //load more var totalItems = $("#myList li").size(); var startIndex = 3; $('#myList li:lt(' + startIndex + ')').show(); $('.loadmore').on('cli ...

Dynamic Selection List Population in jqGrid

Using jqGrid 4.13.3 - free jqGrid In the Add form, there is a static input element and a select list element. The keyup ajax function is bound to the input element using dataEvents in the beforeInitData event. Once the Add form is displayed, entering a va ...

When I try to upload an image onto my website, the layout of my text gets disrupted

There seems to be quite a gap between the welcoming message and the main body text. Significant spacing noticed between Title and body ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

"Error: Cannot iterate over items in React using Item.map, as

I am currently working on implementing a function to handle changes in the names of individuals within an array stored in state as personState. const [personState, setPersonState] = useState([ { id:'asdasd', name: "Max", age ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...