Table of Contents
Vue Top 20 Artists
{{artist.name}}
Vue Top Artist Countries
{{artist.name}} from {{artist.country}}
{{ title }}
Home Web Front-end Vue.js Using props to pass data to subcomponents in Vue.js

Using props to pass data to subcomponents in Vue.js

Sep 30, 2020 pm 05:55 PM
vue.js

Using props to pass data to subcomponents in Vue.js

In this article, we will look at how to pass data from parent component to child component in Vue.js. This article is suitable for developers of all stages, including beginners.

Before we begin

We can view the use of event emitters in the article How to use event emitters to modify component data in Vue.js Method to pass data and its state from child component to its parent component in vue.js.

Before reading this article, you should already know the following points.

You will need the following on your computer:

  • Node.js version 10.x and above installed. You can verify that it is installed by running the following command in Terminal/Command Prompt:

node -v
Copy after login
  • Code Editor: Visual Studio Code is recommended

  • The latest version of Vue, has been installed globally on your computer

  • Vue CLI 3.0 has been installed on your computer. To do this, first uninstall the old CLI version:

npm uninstall -g vue-cli
Copy after login

and then install a new one:

npm install -g @vue/cli
Copy after login
  • Download one here Vue Getting Started Project

  • Extract the downloaded project

  • Navigate to the unzipped file and run the command to keep all dependencies Relationship Latest:

npm install
Copy after login

Efficiency Issue

If you have a data object (like top ten billboard artists List), you want to use two different components to display, but in very different ways, then your first reaction is to create these two independent components, add arrays to the data object, and then display them in the template.

This solution is very good, but when you add more components, it becomes a non-efficient solution. Let's demonstrate this using the starter project you have open in vs code.

Demo

Open the test. Copy the vue file into the code block below:

<template>
  <div>
    <h1 id="Vue-nbsp-Top-nbsp-nbsp-Artists">Vue Top 20 Artists</h1>
    <ul>
      <li v-for="(artist, x) in artists" :key="x">
      <h3 id="artist-name">{{artist.name}}</h3>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: &#39;Test&#39;,
  data (){
    return {
      artists: [
       {name: &#39;Davido&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;Burna Boy&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;AKA&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Sarkodie&#39;, genre: &#39;hiphop&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Stormzy&#39;, genre: &#39;hiphop&#39;, country: &#39;United Kingdom&#39;},
       {name: &#39;Lil Nas&#39;, genre: &#39;Country&#39;, country: &#39;United States&#39;},
       {name: &#39;Nasty C&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Shatta-walle&#39;, genre: &#39;Reagae&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Khalid&#39;, genre: &#39;pop&#39;, country: &#39;United States&#39;},
       {name: &#39;ed-Sheeran&#39;, genre: &#39;pop&#39;, country: &#39;United Kingdom&#39;}
      ]
    }
  }
}
</script>
Copy after login

Create a new file in the "Components" folder, name it test2.vue and paste the code block below Go to it:

<template>
  <div>
    <h1 id="Vue-nbsp-Top-nbsp-Artist-nbsp-Countries">Vue Top Artist Countries</h1>
    <ul>
      <li v-for="(artist, x) in artists" :key="x">
      <h3 id="artist-name-nbsp-from-nbsp-artist-country">{{artist.name}} from {{artist.country}}</h3>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: &#39;Test2&#39;,
  data (){
    return {
      artists: [
       {name: &#39;Davido&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;Burna Boy&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;AKA&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Sarkodie&#39;, genre: &#39;hiphop&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Stormzy&#39;, genre: &#39;hiphop&#39;, country: &#39;United Kingdom&#39;},
       {name: &#39;Lil Nas&#39;, genre: &#39;Country&#39;, country: &#39;United States&#39;},
       {name: &#39;Nasty C&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Shatta-walle&#39;, genre: &#39;Reagae&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Khalid&#39;, genre: &#39;pop&#39;, country: &#39;United States&#39;},
       {name: &#39;ed-Sheeran&#39;, genre: &#39;pop&#39;, country: &#39;United Kingdom&#39;}
      ]
    }
  }
}
</script>
<style scoped>
li{
    height: 40px;
    width: 100%;
    padding: 15px;
    border: 1px solid saddlebrown;
    display: flex;
    justify-content: center;
    align-items: center;
  }  
a {
  color: #42b983;
}
</style>
Copy after login

To register the new component you just created, open the app.vue file and copy the following code in it:

<template>
  <div id="app">
    <img src="/static/imghw/default1.png"  data-src="./assets/logo.png"  class="lazy"  alt="Vue logo" >
    <Test/>
    <test2/>
  </div>
</template>
<script>
import Test from &#39;./components/Test.vue&#39;
import Test2 from &#39;./components/Test2&#39;
export default {
  name: &#39;app&#39;,
  components: {
    Test, Test2
  }
}
</script>
Copy after login

Use the VS Code terminal This command launches the application in the development environment:

npm run serve
Copy after login

It should look like this:

Using props to pass data to subcomponents in Vue.js

You can see that if you have about five more components , you must continue to copy the data in each component. Imagine if there was a way to define data in a parent component and then bring it to every child component that needs it, using the property name.

Solution: Vue props

The Vue team provides what they call props, which are custom props that can be registered on any component. Define properties. The way it works is you define data on the parent component and give it a value, then go to the child component that needs that data and pass that value to the prop attribute so that the data becomes a property in the child component.

The syntax is as follows:

Vue.component(&#39;blog-post&#39;, {
  props: [&#39;title&#39;],
  template: &#39;<h3 id="nbsp-title-nbsp">{{ title }}</h3>&#39;
})
Copy after login

You can use the root component (app.vue) as the parent component and store the data, then register props to dynamically access this data from any component that needs it.

Defining data in the parent component

After selecting the root component as the parent component, you must first define the data to be dynamically shared within the root component object. If you have been following this post from the beginning, open the app.vue file and copy the data object code block in the script section:

<script>
import Test from &#39;./components/Test.vue&#39;
import Test2 from &#39;./components/Test2&#39;
export default {
  name: &#39;app&#39;,
  components: {
    Test, Test2
  },
  data (){
    return {
      artists: [
       {name: &#39;Davido&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;Burna Boy&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},
       {name: &#39;AKA&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Sarkodie&#39;, genre: &#39;hiphop&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Stormzy&#39;, genre: &#39;hiphop&#39;, country: &#39;United Kingdom&#39;},
       {name: &#39;Lil Nas&#39;, genre: &#39;Country&#39;, country: &#39;United States&#39;},
       {name: &#39;Nasty C&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;},
       {name: &#39;Shatta-walle&#39;, genre: &#39;Reagae&#39;, country: &#39;Ghana&#39;},
       {name: &#39;Khalid&#39;, genre: &#39;pop&#39;, country: &#39;United States&#39;},
       {name: &#39;Ed Sheeran&#39;, genre: &#39;pop&#39;, country: &#39;United Kingdom&#39;}
      ]
    }
  }
}
</script>
Copy after login

Receive props

After defining the data, enter the two test components and delete the data objects in them. To receive props in a component, you must specify the props you want to receive in that component. Enter the two test components and add specifications in the script section as follows:

<script>
export default {
  name: &#39;Test&#39;,
  props: [&#39;artists&#39;]
}
Copy after login

Register props

Let the vue engine know that you have Some props that are to be dynamically passed to certain sub-components must be specified in the vue instance. This is done in the template section as shown below:

<template>
  <div id="app">
    <img src="/static/imghw/default1.png"  data-src="./assets/logo.png"  class="lazy"  alt="Vue logo" >
    <Test v-bind:artists="artists"/>
    <test2 v-bind:artists="artists"/>
  </div>
</template>
Copy after login

Here we use the v-bind directive to bind the artists (data object in the script section the name of the array) and artists (the name of the prop in the test component), which is the name you set in the section above. In this case, set without the following directive:

<Test artists="artists"/>
    <test2 artists="artists"/>
Copy after login

您将看不到任何输出,Vue编译器甚至ESLint也不会将其标记为错误或警告,因此,请务必注意并记住对每个动态绑定使用V-Bind。

使用道具

设置好道具之后,就可以在组件中使用它,就像数据是在同一组件中定义的一样。这意味着您可以设置方法调用并在我们的演示案例中轻松访问this.artists

强类型道具

您还可以通过强输入道具来确保组件只接收您希望它接收的数据类型。例如,在我们的演示中,通过设置如下身份验证,您可以确保只有数组才能传递到组件:

<script>
export default {
  name: &#39;Test&#39;,
  props: {
    artists: {
      type: Array
    }
  }
}
</script>
Copy after login

因此,每当您添加了一个错误的类型say string时,您将在控制台中收到一个警告,告诉您它得到的类型不是预期的类型。

Using props to pass data to subcomponents in Vue.js

您可以在这里获得本教程的完整代码

结论

在这篇文章中,我们研究了vue道具,以及它们如何通过创建一个数据对象可重用性平台来帮助鼓励dry(不要重复自己的做法)。我们还学习了如何在Vue项目中设置道具。

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Using props to pass data to subcomponents in Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Nov 16, 2022 pm 08:43 PM

vscode itself supports Vue file components to jump to definitions, but the support is very weak. Under the configuration of vue-cli, we can write many flexible usages, which can improve our production efficiency. But it is these flexible writing methods that prevent the functions provided by vscode itself from supporting jumping to file definitions. In order to be compatible with these flexible writing methods and improve work efficiency, I wrote a vscode plug-in that supports Vue files to jump to definitions.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles