What is the process for transforming a razor loop into a Vue.js component?

I am in the process of enhancing a rather basic vue component by transferring more of the code (originally written in razor) into the component itself to increase modularity.

Currently, the component functions more as a container where razor iterates through a list of communities and generates HTML server-side. This generated HTML is then passed through a slot into the component for styling.

My goal is to minimize the code rendered by razor and instead migrate as much logic as possible into the component. While vue offers looping mechanisms like v-for, I'm unsure of the best way to pass data into the component to utilize it effectively.

Since I am new to vue, like many others, I am still learning how to transfer server-side data to components. I've experimented with creating props, but the complexity of the data being produced has posed a challenge for me. I am hoping someone can provide guidance on the most efficient approach to solving this issue!

Thank you in advance!

index.cshtml:

<community-list>
      @foreach (var region in regions)
      {
          var regPage = region.Pages.FirstOrDefault();
          if (regPage == null)
          {
              continue;
          }
          string isActive = "";
          int communityCount = 0;
          var cities = region.Children;
          for (int i = 0; i < cities.Count; i++) {
              communityCount += cities[i].Pages.Count;
          }
          if (HttpContext.Current.Request.IsAuthenticated && !Model.IsPreview) {
              var email = HttpContext.Current.User.Identity.Name;
              isActive = CompanyName.Core.Models.Users.IsRegionSubscribed(email, region.Name) ? "active" : "";
          }
        <div class="community container primary @isActive" data-name="@region.Name">
          <figure style="background-image: url('/assets/images/@regPage.GetAttributeValue("HeroImage")');"></figure>
          <h3>@regPage.GetAttributeValue("Title")</h3>
          <p>@(communityCount.ToString()) New Home Communities</p>
          <custom-button destination="@regPage.URL" appearance="primary" type="link" size="extra-large" text="Find New Homes in @stateName"></custom-button>
        </div>
      }
    </community-list>

CommunityList.vue

<template>
  <section class="community-list">
    <slot></slot>
  </section>
</template>

<script>
  export default {
    name: 'CommunityList',
  };
</script>

<style lang="scss" scoped>
  -- styling here --
</style>

Update

------

To provide further clarification:

If it is deemed appropriate, I aim to extract the HTML from the razor loop out of the slot and embed it into the component. The objective is to eliminate the slot entirely, and utilize the data from razor to populate the HTML in the component with the returned values from razor.

It appears that relocating more HTML and logic into the component would be advantageous.

Possibly something like:

index.cshtml:

@foreach (var region in regions) {
  var foo = region.foo;
  var bar = region.bar;
}
<community-list foo="@foo" bar="@bar"></community-list>

CommunityList.vue

<template>
  <section v-for="region in regions">
    <p>{{ foo }}</p>
    <p>{{ bar }}</p>
  </section>
</template>

I am uncertain of the most appropriate vue-centered approach. If I convert the razor to generate a list of variables to utilize as shown above, how can I pass that data into the component and loop through it within the vue component itself (similar to the example above)? In the provided case, this may not work, but I believe there must be a way to achieve the desired outcome somehow?

(Or perhaps I am approaching this problem incorrectly altogether?)

Answer №1

To display the information in a tag using razor, store the data in a global variable. This global variable can then be used to initialize the data function when setting up your vue component.

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

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Exploring the Interaction Between Node.js and a Windows 10 Server on a Local Machine

I am curious about the interaction between Nodejs Server and a local machine. Specifically, I would like to understand how tasks such as: Thread Level CPU Cycle Socket Level IO Any help in clarifying this process would be greatly appreciated. ...

Encountering an issue: Unable to initiate a local server when running `npm start`

Currently diving into the world of React, I successfully set up a React app. However, upon running npm install after typing cd davidsapp, I encountered numerous warnings and errors. Subsequently, when issuing the command npm start, all of the errors are di ...

IntelliJ employs varying indentation styles within a single .vue file

When working within the <template> section in Intellij, I noticed that it uses 2 spaces for indentation, while for the <script> part, it uses 4 spaces. This inconsistency is causing errors when running npm run dev. I have configured Intellij t ...

The attempt to compress the code in the file from './node_modules/num2persian' using num2persian was unsuccessful

I have been using the num2persian library to convert numbers into Persian characters. However, whenever I run the command npm run build, I encounter the following error: An error occurred while trying to minimize the code in this file: ./node_modules/num ...

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Checking punctuation in VB.Net is an essential task that can

I am currently working on a keypress event that restricts input to only numbers. Here is the code snippet: Private Sub txtWeight_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtWeight.KeyPress If Not Char.IsNumber(e.KeyChar) Then ...

Guide to sorting a JavaScript array using a filter object

Using a dynamically generated filter object from a multi-search UI component, the data needs to be filtered based on the criteria. Once the user initiates a search, the data will be filtered accordingly. Below is an example of the filter object and sample ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Using AngularJS ng-model to select options in a dropdown menu with WebDriver

In the following code snippet, an AngularJS based dropdown menu is implemented: <select _ngcontent-c1="" class="form-control ng-pristine ng-valid ng-touched"> After opening the list, I attempted to select a variable from this list using the code be ...

trigger a border hover effect on an HTML element

Is it possible to attach a mouseover event specifically to the left border of a div element in HTML? The div serves as a container for various other intricate HTML elements, each with their own mouseover events. While binding a mouseover event to the enti ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Exploring the Ins and Outs of Debugging JavaScript in Visual Studio Using

I encountered a peculiar issue while testing some code. When the program is executed without any breakpoints, it runs smoothly. However, if I introduce a breakpoint, it halts at a certain point in the JSON data and does not allow me to single-step through ...

Converting JavaScript to PHP and encountering problems with POST encoding

Trying to send a string from JavaScript on the client-side to a PHP script on the back-end. The string has special quotes like ’ and “. When checking the console in Chrome, the POST headers show these special characters as they are. On the PHP side, I ...

Drop items next to the specified keys. Vanilla JavaScript

I am trying to create a new array of objects without the gender field. Can you identify any mistakes in my code? let dataSets = [ { name: "Tim", gender: "male", age: 20 }, { name: "Sue", gender: "female", age: 25 }, { name: "Sam", gender: "m ...

Clicking React useState causes it to update before the intended click is registered

My goal is to create 50 buttons that, when clicked, will update the value of useState to the current button number (array index+1). However, I've encountered an issue where I have to click a button twice to get the correct value. The first click alway ...

What is the method for transforming an array into an object with properties (JSON) in JavaScript or ES6?

Here is the array that I have: const array = [2,3]; I am looking to transform this array into an object like the following: "media" :[{"mid":"2"},{"mid":"3"}] Any help would be greatly appreciated. ...