vue组件传值

作者: Trowa | 来源:发表于2018-05-05 16:03 被阅读171次

    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>
    

    相关文章

      网友评论

      • IT人故事会:博主加油!我也是开始写不久,哈哈
        Trowa:@IT人故事会 谢谢支持:pray:

      本文标题:vue组件传值

      本文链接:https://www.haomeiwen.com/subject/bgxerftx.html