Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM?

In my specific case, I want my Vue instance to receive the action attribute of a form element.

For example, this is how my HTML would look like (the path is generated using server-side code):

<form action="path/to/script.php" id="my-form">

</form>

This is how my Vue element would be defined:

new Vue({
    el: 'my-form',
    data: {
        action: '' // I want this item to receive 'path/to/script.php' on load
    },
    compiled: function() {
        console.log(this.action); // Should output 'path/to/script.php'
    }
});

I have attempted to achieve this without success. The action in the DOM gets removed to match the action data item:

 <form action="path/to/script.php" v-bind:action="action">

 </form>

Thank you

Answer №1

You are looking for a solution that is not commonly seen, as the viewmodel usually does not extract data from the view but instead supplies it. Therefore, you will need to create a custom directive to achieve this.

The custom directive I have provided below requires the name of an attribute and the name of a data member to perform the assignment.

Vue.directive('initialize', {
  params: ['item','attr'],
  bind: function() {
    this.vm[this.params.item] = this.el.getAttribute(this.params.attr);
  }
});

new Vue({
  el: '#my-form',
  data: {
    action: '' // The intention here is to set this item to 'path/to/script.php' during initialization
  },
  compiled: function() {
    console.log('Action:', this.action); // This should display 'path/to/script.php'
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<form id="my-form" action="path/to/script.php" v-initialize attr="action" item="action">
</form>

Answer №2

I was able to achieve some functionality using props. The action attribute is not directly linked to the data, but it can be accessed within the Vue instance by using this.action.

HTML:

<form action="path/to/script.php" id="my-form">

</form>

Javascript:

new Vue({
    el: '#my-form',
    props: {
        'action'
    },
    compile: function() {
        console.log(this.action); // Outputs 'path/to/file.php'
    }
});

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

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

The string length is not valid in repeat$1 (VueJS) [Issue resolved: the usage of 'continue' is reserved in JavaScript

I encountered the Error in execution of function repeat$1 when trying to compile a basic VueJS template. This error is causing the compilation process to fail. I'm struggling to identify the issue within the template. Here's the code snippet: ( ...

Troubleshooting Problems with jQuery's .remove() Function

I attempted to create a simple game using JS and jQuery, keeping in mind that I am new to both languages. My goal was to create a function that allows users to delete their save within the game. However, despite my efforts, I faced issues with the function ...

Unable to perform a POST request and send JSON data using AJAX with jQuery at the

It seems like there may be a server issue causing this problem, and unfortunately, I don't have access to our server to troubleshoot. I was hoping that someone else might have a solution or could help me understand the root cause of the issue. The is ...

encountering difficulties with parsing JSON data within JQuery script on Laravel 5.2

In my Laravel project, I am attempting to dynamically populate a second dropdown menu based on the value selected in the first dropdown. This process involves using AJAX to update the options available in the second dropdown when a Cinema Hall is selected. ...

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

Receiving an error when attempting to utilize a value from the .env file in createSecretKey function

Currently, my code looks like this: const secretKey = crypto.createSecretKey( Buffer.from(process.env.SECRET, "hex") ); However, I am encountering the following error message: "The value of 'key.byteLength' is out of range. It must be > ...

vue.js throwing error: Unable to access 'getters' property of an undefined object

Within the Form component.vue, there is a substitution of the event object from the getter into the v-model: <template> <form @submit.prevent="submitForm"> <div class="form-group row"> <div c ...

Transferring the Build Output of a Docker Container to the Host Machine

My dockerfile is quite simple: # develop stage FROM node:alpine as develop-stage WORKDIR /app COPY package*.json ./ RUN npm install COPY . . # build stage FROM develop-stage as build-stage RUN npm run build I believe that after running the docker contain ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

Creating a drawImg function on the HTML/JavaScript canvas

Attempting to duplicate a specified section of an image onto a canvas below, but finding that the mirrored section is resizing unexpectedly. For example, if given a map image and trying to replicate a building from it exactly below, why does the mirrored s ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

Enhance your Angularfire experience with $firebaseArray by enabling dynamic counting and summing

Is there a way to dynamically count certain nodes if they are defined? The current implementation requires explicitly calling sum(). app.factory("ArrayWithSum", function($firebaseArray) { return $firebaseArray.$extend({ sum: function() { var ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

comprehending the concept of express and mastering its usage

Can you confirm if my understanding is correct? 1) So, when I write this line of code... const express = require(“express”) I am assigning a "Class" to the variable express. 2) And then, when I call this function... express.jason() Am I correctly ...

The height of divs spontaneously changes after resizing without any instructions

I am developing a jQuery function to vertically center an element. The function is triggered on load and here is the code: JQuery var $window_height; function Centerize(content) { content.css('margin-top', (($window_height - content.height( ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

The discovery of a commitment in the statement. The automation of unwrapping promises within Angular statements has been phased out

Struggling with errors while setting up a new AngularJS project. Here is the code for my app and controller; var app = angular.module('myApp', ['localytics.directives']) .config(['$parseProvider', function ($parseProvide ...