Can VueJS templates be scoped to avoid redundant object names when accessing properties?

I have been tasked with transitioning code from KnockoutJS to VueJS for my employer. In KnockoutJS, there is a directive called with that allows object properties to be referenced without repeating the object name.

How can I achieve this functionality in VueJS? I have explored slot scope and template scope options, as well as attempted to create a custom directive that modifies the data property on the referenced VNode, but unfortunately, I couldn't make it work.

Current Code:

<div v-for="item in items">
  <div>{{item.name}}</div>
  <div>{{item.phone}}</div>
  <div>{{item.value}}</div>
</div>

Pseudo-code:

<div v-for="item in items" v-with="item">
  <div>{{name}}</div>
  <div>{{phone}}</div>
  <div>{{value}}</div>
</div>

I am asking this question for the sake of readability purposes. Although I have completed the task by using repeated object identifiers when referencing its properties, I wanted to inquire if there might be a more efficient way that I'm overlooking.

Someone in the VueJS chat rooms suggested using Vuex store, but their example did not seem to address my specific concern regarding repetitive naming.

Answer №1

If you want to simplify your object in the v-for loop, you can destructure it like this:

<div v-for="{name, phone} in items">

For instance:

new Vue({
    data: {
        items: [
            {
                name: 'John',
                phone: '123-456-7890',
                otherVal: 'hello'
            },
            {
                name: 'Joe',
                phone: '234-567-8901',
                otherVal: 'goodbye'
            }
        ]
    }
}).$mount('#demo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">  
  <div v-for="{name, phone} in items">
    {{ name }} {{ phone }}
  </div>  
</div>

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 modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

The Javascript functionality of SonarQube Scanner seems to be malfunctioning

We are experiencing issues with SonarQube Scanner in relation to javascript/typescript 10:33:14.808 ERROR: C:/Users/marc.donovan/wk/pos-web-framework/packages/pos-web-error-manager/src/index.js file cannot be parsed 10:33:14.811 ERROR: Parse error on line ...

Enhancing the visual appeal of a JSON object with texture using Three.js

Struggling to apply texture to my 3D Dog JSON model exported from clara.io. Tried using Objectloader and Textureloader, but the texture won't load onto the model. The code might be incorrect or in the wrong place. Looked at other examples but no luck ...

How can you specify the environment in Google Tag Manager?

I have integrated google tag manager and google analytics using the vue-gtm plugin found at vue-gtm Within google tag manager, I have set up 3 environments under the same container. In a user-defined variable called GA from environment, I have created a ...

Activity triggered when the child window is refreshed

I'm in the process of making a child window using Javascript with this code: var newWnd = window.open(url); Is there a way for me to know if the child window has been refreshed or not? Are there any specific events that indicate when it happens? Th ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Sum result from jQuery calculation is not desirable

Within my table, the <th> tag is initially set to 0: <th id="total_price" style="text-align:center">0</th> When a new item is sold, its price should be added to the value within this <th>. For example, if the new item costs 20,000 ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object. If the login details are accurate, the backend will respond with a JSON object containing ...

Is it possible to connect various functions or modules using NPM in a single project?

Currently, I have a set of helper functions that I would like to make available globally in the command line. Utilizing the npm link method, I was able to achieve this by following the steps outlined in this guide: { "name": "tool1", ...

Retrieve data from the Twitch API just one time

Is there a way to make 3 requests to the twitch API without needing to refresh the server multiple times? I need to get information about the live stream, the streamer, and the game, but the data from the live stream is not immediately available for fetchi ...

The selected value from the array in the scope model is not appearing correctly in the UI dropdown menu

I apologize for any linguistic errors in my communication. I have encountered an issue with the UI-Select select box while attempting to display data. Despite using a basic array, the ng-model value is returning as undefined. ...

Navigating the browser view across an extensive HTML page without relying on scrollbars

I have a large HTML page (approximately 7000x5000) and I need to be able to move the user's view around with JavaScript. Disabling the ability for the user to scroll by hiding the browser scrollbars using overflow:hidden on the HTML element is easy. ...

The Node.js router was expecting a function, but instead received an object

Whenever I try to initialize a route with app.use() in my routes directory, I encounter an error while calling my router. The error message states that Router.use() requires a middleware function but received an Object. I am unsure about what is causing th ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Ways to apply inline styling with CSS in a React class-based component

Is it possible to apply inline CSS in a React class component? Here is an example of the CSS I have: { font-size: 17px; 
 font-family: Segoe UI Semibold; color: #565656; text-shadow: 0 1px 1px white; } While this CSS works fine ...

How can Vue.js be incorporated into a Pug template without relying on a CDN?

For quite some time now, I've been pondering this question: If I were to install Vue JS or another library using npm, how would I go about loading that specific library into a pug template? Is it even possible? ...

Hiding HTML elements with display=none isn't functioning

Here is my code snippet: <?php if($counter==0) { echo "value of counter = $counter" ?> <script type='text/javascript'> document.getElementById("tt").style.display = "none"; </script> <?php } ?> <htm ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...