zoukankan      html  css  js  c++  java
  • vue组件间传值

    1、通过路由传值

    A组件通过params把参数传递给B组件(触发事件可以是点击事件、钩子函数)
    let params = {
            amount      :item.amount,           //金额
            payment     :item.payment,          //交易方式
            code        :item.code,             //商家代码
            serial_num  :item.serial_num,       //流水号
        }
    this.$router.push({path:'/income/detail',name:'incomeDetail',params:params})
    
    在B组件获取A传递过来的值
    let params = this.$route.params
    

    2、通过Session Storage缓存的形式传值

    在A组件中设置缓存
    const orderData = {'orderId':123456,'price':100}
    sessionStorage.setItem('缓存名称',JSON.stringify(orderData))
    
    在B组件中获取缓存
    const data = JSON.parse(sessionStorage.getItem('缓存名称'))
    

    3、父子组件传值

    原理:父组件通过props向下传递数据给子组件,子组件通过events给父组件发送消息。
    父子传值原理

    3.1 父组件给子组件传值props

    父组件App.vue

    <template>  
       <div id="app">  
           <child :childMessage="content"></child>  
       </div>  
    </template>  
    
    <script>  
    import child from './components/Child'  
    export default {  
        name : 'app'  
        components:{  
            child
        }
        data(){
            return {
                content:'Send Message to Child'
            }
        }
    </script> 
    

    子组件Child.vue

    <template>  
       <div>  
           <h2>child子组件部分</h2>  
           <p>{{childMessage}}</p>  
       </div>  
    </template>  
      
    <script>  
    export default {  
        //方式1
        props: ['childMessage']
        //方式2
        props: {
             childMessage: String  //指定类型
        }
        //方式3
        props : {
            childMessage:{
                type:String, //指定类型,常用类型有 String Number Object Boolean...
                default:''
            },
        }
    }  
    </script>   
    

    3.2子组件给父组件传值

    父组件App.vue

    <template>  
        <child @showMessage="show" :message="message"></child> //监听子组件触发的showMessage事件,然后调用show方法
    </template>  
    
    <script>
    methods: {
        show(message) {
            this.message = message;
        }
    }
    </script>
    

    子组件Child.vue

    <template>
        <div @click="sendMessage"></div>
    </template>
    
    <script>
    methods: {
       sendMessage() {
            this.$emit('showMessage','Send Message to Father'); //触发showbox方法,'the msg'为向父组件传递的数据
        }
    }
    </script>
    
  • 相关阅读:
    sqlserver 时间格式函数详细
    asp.net中session的原理及应用
    asp.net中的cookie
    WCF 应用(一)
    c#操作word文档之简历导出
    浅解多线程
    .net反射详解
    正则表达式、常用的匹配总结
    存储过程详解
    jquery.pagination.js分页
  • 原文地址:https://www.cnblogs.com/littleBit/p/8995009.html
Copyright © 2011-2022 走看看