SoFunction
Updated on 2025-04-06

Detailed explanation of the use of props in Vue

The props property is a communication bridge between parent and child components. What is a parent-child component? From the perspective of child components, his previous instance or component is his parent component. We know that for security considerations, we cannot directly use the data data of the parent component in the component template. Using the props property, we can pass the data of the parent component to the child component.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>propsTest</title>
  <script src="../js/"></script>
</head>
<body>
<div >
  <Child message="I redefined the message of the parent component, but the parent component will not change because there is no binding, haha!!"></Child>
  <hr />
  <input v-model="message"/>
  <Child :message='message'></Child>
</div>
<script>
  ('Child',{
    props: ['message'],
    template: '<span>{{ message }}</span>'
  });
  var vm = new Vue({
    el: '#props',
    data: {
      message: 'Prop'
    }
  });
</script>
</body>
</html>

Code renderings

Process the data of the parent component in the child component. After the data of the parent component is passed into the child component through props, the data can also be processed in the child component, including calculation attributes, data attributes, etc. This avoids operating the data directly in the parent component when the child component needs to process the data. Moreover, due to the unidirectionality of the props data flow, it will not affect the data of the parent component when changing the data in the child component.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>propsTest</title>
  <script src="../js/"></script>
</head>
<body>
<div >
  <input v-model="message"/>
  <Child :message='message'></Child>
</div>
<script>
  ('Child',{
    props: ['message','todos'],
    template: '<span>{{ test }}</span>',
    computed: {
      test: function(){
        return ().toUpperCase();
      }}
  });
  var vm = new Vue({
    el: '#props',
    data: {
      message: 'Prop'
    }
  });
</script>
</body>
</html>

Code renderings

Code renderings

Prop verification

We can specify verification rules for the component's prop. If the incoming data does not meet the requirements, Vue will issue a warning. This is very useful for developing components for others to use.

To specify validation rules, you need to define props in the form of objects, not string arrays

('example',{
  props: {
    propA: String,
    propB: [Number,String]
}
});

Summarize

The above is the use of props in Vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!