• vue的六种传值方式


    六种传值方式为:

    • 属性传值
    • $refs
    • $parent
    • 通知传值(广播传值)
    • 本地传值
    • 路由传值

    一、属性传值

    1.可传值类型

    • 固定值
    • 绑定属性
    • 方法
    • 本类对象

    2.操作步骤

    ①.父组件调用子组件的时候,绑定动态属性 <htitle mess="父组件给子组件传值"></htitle>

    ②. 在子组件里边通过props,接收父组件传过来的值

    3.适用场景

    仅适用于 父组件给子组件传值

    4.属性介绍

    组件属性定义:

     props:["mess","bindMsg","run","fatherThis"],
    

    子组件验证也可传入参数的合法性:

     props:{
            'mess':String,
            'bindMsg':[String, Number],
            'run':Function, 
            'fatherThis':Object,
    }
    

    更多props请查看Vue官网:https://cn.vuejs.org/v2/api/?#props

    5.示例代码

    父组件:

    <template>
      <div id="app">
        <htitle mess="父组件给子组件传值了" :bindMsg="msg" :run="run" :fatherThis="this"></htitle>
      </div>
    </template>
    
    

    子组件

    <template>
        <div class="divfirst">
            <span>{{mess}}</span>
            <h1>{{bindMsg}}</h1>
            <button @click="run()">点击调用父组件方法</button>
            <button @click="getPrasent()">点击获取父组件实体(实体拿到可以使用用父组件的方法和属性了)</button>
        </div>
    </template>
    
    <script>
    export default {
        props:{
            'mess':String,
            'bindMsg':[String, Number],
            'run':Function, 
            'fatherThis':Object,
        },
        data(){
            return {}
        },
        methods:{
            getPrasent(){
                this.fatherThis.run();
                alert(this.fatherThis.msg);
            } 
        }
    }
    </script>
    
    

    二、父组件获取子组件数据

     父组件通过$refs获取子组件的数据和方法

    1.可获取类型

    • 子组件属性
    • 子组件方法

    2.操作步骤

    1.调用子组件的时候调用一个ref
    <v-fgsheader ref="header"></v-fgsheader>
    2.在父组件中通过
    this.$refs.header.属性
    this.$refs.header.方法

    3.适用场景

    子组件给父组件传值

    4.示例代码

    父组件

    <template>
        <div class="FGSHome">
            <v-fgsheader ref="header"></v-fgsheader>
            <button @click="getChildProp()">获取子组件的属性的值</button>
            <button @click="getChildMethod()">获取子组件的方法</button>
        </div>
    </template>
    
    <script>
    import FGSHeader from './FGSHeader.vue'
        export default{
    
            data(){
                return { }
            },
            components:{
                'v-fgsheader':FGSHeader,
            },
            methods: {
              getChildProp(){
                  alert(this.$refs.header.msg);
              },  
              getChildMethod(){
                  this.$refs.header.run();
              }
            },
        }
    </script>
    
    

    子组件

    <script>
        export default{
            data(){
                return {
                    msg:"我是子组件header的值哟"
                }
            },
            methods:{
                run(){
                    alert("这是子组件Header的方法+"+this.msg);
                }
            }
        }
    </script>
    

    三、子组件获取父组件数据

      子组件通过$parent获取父组件的数据和方法,这种传值方式实际上类似于上边的属性传值中父组件给子组件的传递了子类对象this,只不过Vue官方给封装好了。

    1.可获取类型

    • 父组件属性
    • 父组件方法

    2.操作步骤

    直接在子组件中使用this.$parent.XX,不需要做任何多余操作。

    3.适用场景

    父组件给子组件传值

    4.示例代码

    子组件

    getFatherProp(){
        alert(this.$parent.fatherMsg); 
    },
    getFatherMethod(){
        this.$parent.fatherRun();
    }
    

    四、通知传值(广播传值)

    1.可传值类型

    Vue官网只写了[...args],故通知/广播传值我们定为只传基本数据类型,不能传方法。

    2.操作步骤

    1、新建一个js文件 然后引入vue 实例化vue 最后暴露这个实例

    2、在要广播的地方引入刚才定义的实例

    3、通过 VueEmit.$emit('名称','数据')传播数据

    4、在接收收数据的地方通过 $on接收广播的数据
    VueEmit.$on('名称',function(){})

    3.适用场景

    适用于父子组件、兄弟组件间进行传值。
    color{red}{注意:} 无关系组件不能用这种方式传值。(笔者理解是:对于上图中的A、B组件。假设A广播通知,B接收通知。挂载A的时候B卸载了,也就是说B被内存销毁了,B是接收不到广播的)

    4.属性介绍

    对于通知传值而言,可以一人广播,然后多者接收。

    5.示例代码

    vueEvent.js

    import Vue from 'vue'
    var vueEvents = new Vue();
    export default vueEvents;
    

    兄弟组件C(广播者)

    import vueEvents from '../Model/vueEvent.js'
    
    sendEmit(){
          var numbery =  (Math.random()+300).toFixed(3);
          vueEvents.$emit('notifyToNew',this.homeMsg+numbery);
     }
    

    兄弟组件D(接收者)

    import vueEvents from '../Model/vueEvent.js'
    mounted(){
         var _this = this;
         vueEvents.$on("notifyToNew",function(data_P){
                //注意this的作用域
               console.log('广播传过来的值是'+data_P);
              _this.receive = data_P;
        })
    }
    

    五、本地传值

    本地传值方式对于Vue而言有两种,一种是JS的localStorage,另一种Vuex

    1.可传值类型

    localStorage: String(可通过JSON进行json数据与String之间的转化)
    Vuex:方法、数据、异步方法

    2.操作步骤

    2.1 localStorage

    存:

    localStorage.setItem('tolist',JSON.stringify(this.tolist));
    

    取:

    var tolist = JSON.parse(localStorage.getItem('tolist'));
    
    2.2 Vuex

    2.1 src新建一个vuex文件夹
    2.2 vuex文件夹里新建一个store.js
    2.3 安装vuex  cnpm install vuex --save
    2.4 在刚才创建的store.js 中引入vue、vuex 引入vuex 并且use

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    

    2.5 定义数据 state在vuex中用于存储数据

    var state = {  count:1,}
    

    2.6 定义方法 mutations里边放的是方法,方法主要用于改变state里边的数据

    var mutations = {
        incCount(){
                ++state.count;
       }
    }
       //类似于计算属性  state里边的数据改变时候触发的方法。 可以做一些操作 并且可以有返回值
    var getterfl={
             completedCountChange(state){
             return state.count * 2 +'位';
            }
        }
    

    Action 类似于 mutation,不同在于: Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作

    var actionfl = {
      asynIncCount(context){  
    //因此你可以调用context.commit来提交一个mutation  使用action需要用dispatch
          context.commit('incCount');
      }
    }
    

    2.7 实例化 vuex

    const store = new Vuex.Store({
                state,//state: state  简写
                mutations: mutations,//属性的简写是 mutations
        getters:getterfl,
           actions:actionfl,
    })
    

    2.8 对外暴露

    export default  store;
    

    2.9 在需要用的地方引入

    import store from '../vuex/store.js'
    

    2.10 注册store ,放在methods,data同级

    export default {
        data(){
            return{}
        },
        store:store,
        methods:{
            incCount(){
                this.$store.commit('incCount');
            }
        }
    }
    

    2.11 使用vuex
    使用数据:  this.$store.state.count
    调用方法: this.$store.commit('incCount');

    3.适用场景

    父子组件、兄弟组件、无关系组件任意组件之间的传值

    4.品鉴

    Vuex本质上也是一种本地存储,比localStorage的单纯值传递多了方法、属性、异步方法等功能。但是因为是将内容本地化,所以就会被在浏览器中获取到。

    六、路由传值

    color{red}{注意:}
    1.父组件push使用this.$router.push
    2.在子组件中获取参数的时候是this.$route.params

    1 、动态路由传值
       1.1 配置动态路由
          routes:[
             //动态路由参数  以冒号开头
             {path:'/user/:id',conponent:User}
           ]
    
       1.2 传值
         第一种写法 :  <router-link :to="'/user/'+item.id">传值</router-link>
         第二种写法 : goToUser(id) {
                        this.$router.push( {path:'/user/'+id});
                      }
       1.3 在对应页面取值
           this.$route.params;  //结果:{id:123}
    
    2、 Get传值(类似HTMLGet传值)
     2.1 配置路由
         const routes = [{path:'/user',component:User},]
     2.2 传值  
         第一种写法 : <router-link :to="'/user/?id='+item.id">传值</router-link>
         第二种写法 : goToUser(id) {
                            //'user' 是路径名称
                          this.$router.push({path:'user',query:{ID:id}});
                      }
     2.3 在对应页面取值
         this.$route.query;  //结果 {id:123}
    

    Tips:路径传递参数会拼接在URL路径后

    3 、命名路由push传值
    3.1 配置路由
       const routes = [{path:'/user',name: 'User',component:User},]
    3.2 传值  
            goToUser(id) {
                    //'User' 是路径重命名
                  this.$router.push({name:'User',params:{ID:id}});
               }
    3.3 在对应页面取值
           this.$route.params;  //结果:{id:123}
    

    Tips:命名路由传递参数不在URL路径拼接显示

    结束语

    单一组件间建议使用属性传值单,一对多传值建议广播传值,路由传值需配合路由进行处理,全局性的值(敏感信息除外)使用本地缓存传值。父子组件间传值使用$refs、$parent。组件各种传值方式各有优劣,诸君请按实际情况选取。

  • 相关阅读:
    什么是Servlet容器?
    JAVA
    BIO与NIO、AIO的区别(这个容易理解)
    深入分析JAVA IO(BIO、NIO、AIO)
    Undertow
    Consul CAP理论纠错
    JAVA BIO与NIO、AIO的区别
    Java-线程池专题(什么是线程池,如何使用,为什么要用)
    java中的重量级与轻量级概念
    Postman 把response的值自动放到变量里
  • 原文地址:https://www.cnblogs.com/ming1025/p/13073753.html
Copyright © 2020-2023  润新知