Vue Error: The function slugify is not defined

Currently, I am working on a feature where I want to extract the value from one input field, convert it into a slug format, and display it in another input field. This project involves Laravel Spark, Vue, and Bootstrap 4.

Here is the content of my listings.blade.php:

<createlisting inline-template>
  <div class="container">
    
  <h1>
    Create a listing
  </h1>
  <form class="form">
      <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" v-on:keyup="listingslug" id="name" name="name" placeholder="Example input placeholder">
  </div>
      <label for="slug">Your vanity URL</label>
<div class="input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text" id="basic-addon3">{{ env('APP_URL') }}/listing/</span>
  </div>
  <input type="text" class="form-control" id="slug" name="slug" aria-describedby="basic-addon3">
</div>
  </form>
</div>
</createlisting>

The above code snippet is included in a file named createlisting.js.

Vue.component('createlisting', {
    data() {
        return {
            form: new SparkForm({
                name: '',
                description: ''
            })
        };
    },
    methods: {
      slugify: function(text) {
        return text
          .toString()
          .toLowerCase()
          .normalize('NFD')
          .trim()
          .replace(/\s+/g, '-')
         .replace(/[^\w\-]+/g, '')
          .replace(/\-\-+/g, '-');
      },
      listingslug: function(text) {
        document.getElementById("slug").value = this.slugify(text); 
      }
    }
});

I have also included a similar slugify function from my custom.js file within the Vue component for testing purposes.

/**
*   This is the slugify function, to allow us to slugify text
*/
function slugify(text) {
  return text
    .toString()
    .toLowerCase()
    .normalize('NFD')
    .trim()
    .replace(/\s+/g, '-')
    .replace(/[^\w\-]+/g, '')
    .replace(/\-\-+/g, '-');
}

As someone who is relatively new to Vue and still learning Javascript, I am encountering an issue where changing slugify(text) in the Vue template to this.slugify(text) resulted in an output of "object-keyboardevent". Any insights on what might be going wrong?

Answer №1

One issue at hand is the improper binding of input text for 'slugification' in your Vue application.

To correctly bind the input text, use v-model like this:

//Placeholder and keyup event removed for simplicity

<input type="text" class="form-control" id="name" name="name" v-model="name">

Refer to Vue documentation on form input bindings using v-model: https://v2.vuejs.org/v2/guide/forms.html

Instead of keyup, consider using a button with @click to trigger the method 'listingslug':

<button @click="listingslug">Slugify</button>

For more information on events, consult the official Vue documentation: https://v2.vuejs.org/v2/guide/events.html

The output of the 'slugified' input can be tied to a data value as shown below:

<input type="text" class="form-control" id="slug" name="slug" value="{{slugified}}" aria-describedby="basic-addon3">

To make this work, ensure 'slugified' is included in your data attributes and initialized as an empty string or NULL (similar to 'name').

Adjust your listingslug method accordingly:


listingslug: function() {
        this.slugified = this.slugify(this.name); 
      }

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

Is there a way to modify the props.data in a child component?

I need assistance with displaying a range from an array that is passed into a child component. Currently, my Parent component looks like this: import data from './data.json' return ( <Cell symbol={data.symbol} number={data.number} /> ) ...

Tips for adjusting the font size of choices within the Material UI autocomplete component

Hey there, I'm currently working on a project using the Material Table and I'm looking to adjust the font size of the options in the Material UI Autocomplete. Any tips would be greatly appreciated! Thanks https://i.sstatic.net/ZM17w.png import R ...

Retrieve a targeted table from a webpage through Ajax refresh

On a webpage, I have a table that has two different views: simple and collapsible. I want to be able to toggle between these views using a button click without the need to refresh the entire page. Below is the code snippet I am currently using: $(&apo ...

What is a sophisticated approach to overriding a jQuery method specifically within a plugin?

Today, my brain is in a bit of a fog where I can't seem to find an elegant solution to this issue. I've recently come into possession of a plugin that I need to tweak in order to pass an enabled or disabled state to it, allowing it to detach all ...

What is the best way to assign a transition name property in Vue.js?

Is it possible to dynamically bind the transition name property in Vue.js? <transition-group :name="{ transactionAnimation: isActive }" tag="tbody" class="list-group" > //.... some code </transition-group&g ...

Stopping the PanResponder in React Native temporarily: A guide

Here is the snippet to create an instance of the panResponder: constructor( props ) { super( props ); this.position = new Animated.ValueXY(); this.panResponder = PanResponder.create( { onStartShouldSetPanResponder: ( ) => true, ...

Exploring the variations in module definitions with requireJS

Struggling with requireJS right now. It's an AMD which means it's asynchronous. Typically, a module would be defined like this: define("some Name", ["./moduleOne"], function(moduleOne){ //this would be undefined moduleOne.whatEver(); v ...

Error encountered when attempting to dynamically alter property values of an object using Typescript

Can anyone help me figure out how to dynamically change object property values based on the property type in Typescript? I want to replace all string properties with "***", but I keep running into an error that says Type '"***"' is not assignable ...

Error: The object 'require' is not recognized in Vue Component

I am facing an issue while using screenfull.js (import screenfull from "screenfull") in a Vue component. Can anyone help me with this problem? Here is the error information. Version: Vue: 2.6.14 @vue/cli-service: 5.0.4 Babel-loader: 8.2.5 Vue-loader: ...

Comparison of performance between serializing an object to indexedDB and using JSON.stringify

I am curious about the efficiency differences in terms of browser/CPU/memory between using JSON.stringify for serialization versus writing an object to an object store in indexedDB. The context for this question is optimizing the process of writing an obj ...

Integrate retrieved JSON data using Ajax into D3 visualizations

Could someone please guide me on how to incorporate fetched JSON data using Ajax into D3? I've integrated this example here into my project and now I just want to populate the radial layout with my own data. The image below shows the current bilevel r ...

Tips for including items in a list nested within a dictionary using JavaScript

I'm currently working with a JavaScript dictionary and I need to insert an element into a list that belongs to a specific key within the dictionary. Check out the code snippet below: lines = [ [1,2], [2,4], [2,3], [3,5] ]; nodes = [ ...

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

MongoDB: Restrict the number of records returned to an increasing count within a specified range

Currently, I am working on a Node project that uses Mongoose. In my code, I have the following query: var query = Model.aggregate( { $match: { id: id } }, { $sort: { created: -1 } }, { $project: { name: ...

`Vue Router - Dynamically update route anchor on scroll`

My goal is to achieve the same routing behavior on my website as demonstrated here: https://router.vuejs.org/guide/#html. If you observe, the link changes to https://router.vuejs.org/guide/#javascript when you scroll down, and reverts when scrolling back u ...

Guide on creating a nested commenting platform with express.js

My goal is to set up a system for displaying multi-level comments, where a comment can have replies, which in turn can also have replies, and so on. Currently, I am using SQLite for this purpose. Below is the approach I have taken so far: Model const Comme ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Encountering an error in Express while attempting to upload an image due to the inability to read the property 'file' of undefined

I am currently learning Express framework. I encountered an error while trying to upload an image using Express. The error message I received is "Cannot read property 'file' of undefined." Below are the code snippets that I am using, and I&apo ...

What is the reason for the presence of additional mandatory dependencies in the package-lock.json file?

The recent release of React includes breaking changes to the TypeScript typings, causing packages that require "@types/react" with a wildcard version to automatically target this new version and break my project. Initially, I wanted to reach out to projec ...

Update the variable in a PHP script and execute the function once more without the need to refresh the page

Hey there, I'm wondering if AJAX is necessary for the functionality I want to implement. Here's the scenario: I have a function that generates a calendar and I plan to add 'forward' and 'backward' arrows so users can navigate ...