Vue中$emit()方法和props属性的区别与应用

Vue中$emit()方法的应用

首先,对于$emit()方法的相关定义,大家请看emit( eventName, […args] )

  1. 父组件可以通过自定义属性给子组件传值,子组件通过props属性监听父元素传过来的数据
  2. 子组件可以使用$emit调用父组件的方法并传递数据

**ps:**这里我感觉应当是重要的事情说三遍!三遍!!三遍!!!
我看了很多人的博客,第一条大家都是写父组件可以使用 props 把数据传给子组件 ,我感觉这句话有失偏颇

1.父组件向子组件传值

有关props:

props只能是父组件向子组件进行传值,props使得父子组件之间形成了一个单向下行绑定。子组件的数据会随着父组件不断更新。
props 可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以传递一个函数。
props属性名规则:若在props中使用驼峰形式,模板中需要使用短横线的形式

下面是一个例子,大家可以看一下

<!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>

下面是用脚手架的例子
父组件

// 父组件
<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>

子组件

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

2.子元素向父元素传值

$emit绑定一个自定义事件,当这个事件被执行的时就会将参数传递给父组件,而父组件通过v-on监听并接收参数
父组件

<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>

子组件

<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>

猜你喜欢

转载自blog.csdn.net/m0_56026872/article/details/118684741