The difference and application of $emit() method and props attribute in Vue

Application of $emit() method in Vue

First of all, for the relevant definition of the $emit() method, please see emit(eventName, […args])

  1. The parent component can pass values ​​to the child component through custom attributes, and the child component listens to the data passed by the parent element through the props attribute.
  2. Child components can use $emit to call the parent component's methods and pass data

**ps:** I feel like I should say important things here three times! Three times! ! Three times! ! !
I read a lot of people's blogs. The first one is that parent components can use props to pass data to child components . I feel that this sentence is biased.

1. Parent component passes value to child component

About props:

Props can only pass values ​​from parent components to child components. Props form a one-way downward binding between parent and child components. The data of child components will be continuously updated with the parent component.
Props can explicitly define one or more data. The received data can be of various data types, and a function can also be passed.
Props attribute name rules: If you use camel case in props, you need to use dash form in the template

Here is an example, you can take a look

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组</title>
    <style>
        .wx-user-wrapper{
      
      
            width: 100px;
            height: 100px;
            border: orangered 1px solid;
        }
        .vipClass{
      
      
            font-weight: 700;
            color: peru;
        }
        .wx-star-wrapper{
      
      
            
            width: 100px;
            border: orangered 1px solid;
            display: flex;  
            flex-direction: column;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 
            v-for循环组件的时候  需要加上key属性  而且key的属性要唯一
            key还必须为string或number
            所以我们通常用v-for 循环时候的index
         -->
        <component-list v-for="(user,index) in users" :user="user" :key="index"> </component-list>
        <component-star :users="users"></component-star>
    </div>

    <script type="text/html"  id="wx-star">
        <div class="wx-star-wrapper">
            <div v-for="(star,index) in users" :key="index">
                <p>用户名:{
      
      {
      
      star.name}}</p>
                <p>年龄:{
      
      {
      
      star.age}}</p>
            </div>
            
        </div>
    </script>


    <script type="text/html"  id="wx-user">
        <div class="wx-user-wrapper">
            <p :class="{vipClass:user.vip}">用户名:{
      
      {
      
      user.name}}</p>
            <p>年龄:{
      
      {
      
      user.age}}</p>
        </div>
    </script>
    <script src="../js/vue.js"></script>
    <script>
        // 传对象
        Vue.component("component-list",{
      
      
            template:"#wx-user",
            props:["user"]
        })
        // 传数组
        Vue.component("component-star",{
      
      
            template:"#wx-star",
            props:["users"]
        })
        Vue.component("component-list",{
      
      
            template:"#wx-user",
            props:["user"]
        })
        new Vue({
      
      
            el:"#app",
            data:{
      
      
                users:[
                    {
      
      name:"沈腾",age:40,vip:false},
                    {
      
      name:"贾玲",age:35,vip:false},
                    {
      
      name:"张小斐",age:28,vip:false},
                    {
      
      name:"王宁",age:36,vip:true}
                ]
            }
        })
    </script>
</body>
</html>

The following is an example of using scaffolding.
Parent component

// 父组件
<template>
    <div id="father">
        <child :msg="msg" :fn="logVue()"></child>
    </div>
</template>

<script>
import childfrom "./child.vue";
export default {
    
    
    name: father,
    data() {
    
    
        msg: "父组件数据";
    },
    methods: {
    
    
        logVue() {
    
    
            console.log("vue");
        }
    },
    components: {
    
    
        child
    }
};
</script>

Subassembly

// 子组件
<template>
    <div id="child">
        <p>{
    
    {
    
    msg}}</p>
        <button @click="fn">按钮</button>
    </div>
</template>
<script>
export default {
    
    
    name: "child",
    props: ["msg", "fn"]
};
</script>

2. Child elements pass values ​​to parent elements

$emit binds a custom event. When this event is executed, the parameters will be passed to the parent component, and the parent component listens and receives parameters through v-on.
Parent component

<template>
  <div>
  	<!-- 这里@后面绑定的事件名,必须和子组件中$emit方法传过来的事件名一致 -->
      <child @changeMsg="change">子组件</child>
  </div>
</template>

<script>
import Child from './Child.vue'
export default {
    
    
  name: 'Father',
  components: {
    
     Child },
  data () {
    
    
      return {
    
    
          msgData: ''
      }
  },
  methods: {
    
    
  //这个方法监听到了子组件通过$emit传过来的参数
      change (msg) {
    
    
          this.msgData = msg
          console.log(this.msgData);
      }
  }
}
</script>

Subassembly

<template>
  <div>
  <!-- 点击按钮触发点击事件的同时,会把自定是的事件作为参数传递给父组件 -->
      <button @click="clickFn">向父组件传值</button>
  </div>
</template>

<script>
export default {
    
    
    name: 'Child',
    data () {
    
    
        return {
    
    
            msg: "子组件数据"
        }
    },
    methods: {
    
    
       clickFn () {
    
    
       //第一个参数,事件名,第二个参数,要传递的数据
           this.$emit('changeMsg',this.msg)
       } 
    }
}
</script>

<style>

</style>

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/118684741