How can you utilize a computed property in a Vue component to select all the text within it?

When using $event.target.select(), I usually can select all the text. However, in this scenario, it seems to be selecting everything and then replacing the selection with the computed property. How can I select all after the computed property has finished?

Vue.component('my-component', {
  template: `
<div>
My Component
<input type="text" v-model="displayValue" @blur='isInputActive = false' @focus='isInputActive = true;$event.target.select()'></input>
</div>
`,
  props:['value'],
    data() {
        return {
            isInputActive: false
        };
    },
    computed: {
        displayValue: {
            get: function() {            
                return (this.isInputActive) ? this.value : this.value.toUpperCase();
            },
            set: function(val) {
              this.$emit('input', val);
            },
        }
    },
})

new Vue({
  el: '#app',
  data() {
        return {
            test: "Test"
        };
    },  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <my-component v-model="test"></my-component>
</div>

Answer №1

Utilize the $nextTick method to execute the callback function once the computed property is completed.

@focus='isInputActive = true; $nextTick(() => $event.target.select())'

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

Tips for stopping ajax requests from automatically following redirects in jQuery

When utilizing the jQuery ajax functions to connect with a web service, I encounter an issue where the server redirects the response to a page with a 200 status code instead of providing a proper status code indicating an error. Unfortunately, I am unable ...

What's causing this javascript to malfunction on the browser?

I encountered a problem with the code in my .js file. Here is a snippet of the code: $.extend(KhanUtil, { // This function takes a number and returns its sign customSign: function(num){ num = parseFloat(num) if (num>=0){return 1} ...

When the input CTRL+C is entered in the console, Node.js / JavaScript will output

I have a script that I use to restart another script. Here is the code snippet: catch(err){ console.log(err) webhook.send(`Error monitoring **www.-.com**, restarting monitor.`) await browser.close() await sleep(monitorDelay) return chec ...

Exploring issues with jQuery

I'm encountering an issue with my code. I have multiple divs with the same classes, and when I click on (toggle#1) with the .comments-toggle class, all divs below toggle-container expand. What I actually want is for only the div directly below .commen ...

Implementing $modal.open functionality in AngularJS controller using Ui-Bootstrap 0.10.0

Is there a way to properly call $modal.open from the controller in AngularJS since the removal of the dialog feature in ui-bootstrap 0.1.0? What is the alternative method available in the current version? In previous versions like 0.1.0, it was simply don ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

Creating a file structure for JavaScript files in a Vue CLI project

When structuring my Vue CLI project, I'm struggling to find clear documentation on best practices. Currently, I have 10 modules each with an associated JS file. My approach so far involves organizing all the pages in my router.js within a views direc ...

Creating a truly dynamic component in Vue/Nuxt: A step-by-step guide

To implement a truly dynamic single page component, we can utilize the component tag like this: <component v-bind:is="componentName" :prop="someProperty"/> ... import DynamicComponent from '@/components/DynamicComponent.vue'; ... compon ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...

When creating a dynamic page number using JavaScript during a print event, the height of an A4 page is not taken into

While creating my A4 invoice using HTML, CSS, and JS, everything appears correctly in the print preview. However, I am encountering an issue where the page number is not aligned properly and extra empty pages are generated automatically. Below is a snippe ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Unable to switch the text option

[Fiddle] I'm currently working on a project where I want pairs of buttons to toggle text by matching data attributes. While I can successfully change the text from "Add" to "Remove" on click, I am facing an issue with toggling it back to "Add" on the ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

What is the best way to design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

Transfer properties to the children of this component

I'm a beginner with React and facing an issue when trying to pass custom props to this.props.children. I attempted using React.cloneElement, and while I can see the prop in the console.log within the class where I created it, it seems to get lost duri ...

Utilize the same Apollo GraphQL query definition across various Vue components for different properties

On my vue screen, I am trying to utilize a single apollo graphql query that I have defined for two different properties. From what I understand, the property name must correspond with an attribute name in the returned json structure. I attempted to use the ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...