Home Web Front-end Vue.js How to implement a prompt-like popup box in Vue?

How to implement a prompt-like popup box in Vue?

Jun 25, 2023 pm 12:52 PM
vue prompt Pop-up box

How to implement a prompt-like pop-up box in Vue?

In front-end development, pop-up boxes are very common components, especially pop-up boxes similar to prompt. The Vue framework provides us with many components, but there is no component that directly implements the prompt pop-up box. So how to implement a pop-up box similar to prompt in Vue? This article will briefly introduce several implementation methods.

Method 1: Use Vue’s own $emit

In Vue, each Vue instance has a built-in $emit method. You can use it to customize events and listen for this event in the component. We can use this feature to implement pop-up boxes.

First, in the component that needs to pop up the pop-up box, you can use $emit to customize an event. In this event, you can pass the parameters required by the pop-up box:

Vue.component('prompt', {
  template: `
    <div>
      <div v-if="visible" class="mask">
        <div class="prompt-box">
          <h3>{{title}}</h3>
          <input type="text" v-model="inputValue">
          <button @click="close('cancel')">取消</button>
          <button @click="close('ok')">确定</button>
        </div>
      </div>
    </div>
  `,
  props: {
    title: {
      type: String,
      default: '请输入'
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputValue: ''
    }
  },
  methods: {
    close(val) {
      if (val === 'ok') {
        this.$emit('ok', this.inputValue)
      } else {
        this.$emit('cancel')
      }
    }
  }
})
Copy after login

Then in the parent component, Listen to this custom event and use v-model to two-way bind the value of the input box:

<template>
  <div>
    <button @click="showPrompt = true">弹出提示框</button>
    <prompt title="请输入内容" :visible="showPrompt" @cancel="showPrompt = false" @ok="handleOk"></prompt>
  </div>
</template>
 
<script>
import Prompt from './prompt.vue'
export default {
  components: {
    Prompt
  },
  data() {
    return {
      showPrompt: false,
      inputValue: ''
    }
  },
  methods: {
    handleOk(val) {
      this.showPrompt = false
      this.inputValue = val
    }
  }
}
</script>
Copy after login

Method 2: Use Vuex state management

If the pop-up box needs to be used in multiple components , and many parameters need to be passed, which can be achieved using Vuex state management.

First, add a new state in Vuex to store the status and parameters of the pop-up box:

state: {
  isPromptShow: false,
  promptData: {
    title: '',
    inputPlaceholder: '',
    inputValue: ''
  }
}
Copy after login

Then, in the component that needs to pop up the pop-up box, use the $store.commit method to modify it isPromptShow and promptData status:

methods: {
  showPrompt() {
    this.$store.commit('setPromptData', {
      isPromptShow: true,
      promptData: {
        title: '请输入',
        inputPlaceholder: '请输入内容',
        inputValue: ''
      }
    })
  }
}
Copy after login

In the component of the pop-up box, you can use mapState and mapMutations to obtain the status in Vuex and submit mutations, thereby realizing the event response logic of the pop-up box:

<template>
  <div v-if="isPromptShow" class="mask">
    <div class="prompt-box">
      <h3>{{promptData.title}}</h3>
      <input type="text" :placeholder="promptData.inputPlaceholder" v-model="promptData.inputValue">
      <button @click="closePrompt('cancel')">取消</button>
      <button @click="closePrompt('ok')">确定</button>
    </div>
  </div>
</template>
 
<script>
import { mapState, mapMutations } from 'vuex'
export default {
  computed: {
    ...mapState(['isPromptShow', 'promptData'])
  },
  methods: {
    ...mapMutations({
      setPromptData: 'SET_PROMPT_DATA'
    }),
    closePrompt(val) {
      if (val === 'ok') {
        this.$emit('ok', this.promptData.inputValue)
      } else {
        this.$emit('cancel')
      }
      this.setPromptData({ isPromptShow: false })
    }
  }
}
</script>
Copy after login

Change the state of isPromptShow in vuex

mutations: {
  SET_PROMPT_DATA(state, data) {
    state.isPromptShow = data.isPromptShow
    state.promptData = data.promptData
  }
}
Copy after login

In the parent component, you not only need to use Vuex's mapState to obtain isPromptShow and promptData, but also need to use mapActions to call the method of submitting mutations in Vuex:

<template>
  <div>
    <button @click="showPrompt">弹出提示框</button>
    <prompt v-if="isPromptShow" @ok="handleOk" @cancel="closePrompt"></prompt>
  </div>
</template>
 
<script>
import Prompt from './prompt.vue'
import { mapState, mapActions } from 'vuex'
export default {
  components: {
    Prompt
  },
  computed: {
    ...mapState(['isPromptShow', 'promptData'])
  },
  methods: {
    ...mapActions(['setPromptData']),
    showPrompt() {
      this.setPromptData({
        isPromptShow: true,
        promptData: {
          title: '请输入',
          inputPlaceholder: '请输入内容',
          inputValue: ''
        }
      })
    },
    closePrompt() {
      this.setPromptData({ isPromptShow: false })
    },
    handleOk(val) {
      console.log(val)
      this.setPromptData({ isPromptShow: false })
    }
  }
}
</script>
Copy after login

Method 3: Use a third-party library

If you think the above two methods are too troublesome, you can actually consider using a third-party library to implement a prompt-like pop-up box. Currently popular third-party libraries include ElementUI, Vuetify, iView, etc. These libraries provide pop-up components similar to prompt, which are very practical.

For example, there is a MessageBox pop-up box in the ElementUI component library:

this.$confirm('内容', 'title', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
}).then(() => {
  // 点击确定回调
}).catch(() => {
  // 点击取消回调
})
Copy after login

Summary

This article mainly introduces three methods to implement a prompt-like pop-up box in Vue. They are using $emit, using Vuex state management and using third-party libraries. Each method has its own characteristics and applicable scenarios, and needs to be selected according to specific circumstances.

The above is the detailed content of How to implement a prompt-like popup box in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

See all articles