vue中組件傳值方式匯總


在應用復雜時,推薦使用vue官網推薦的vuex,以下討論簡單SPA中的組件間傳值。

一、路由傳值

  路由對象如下圖所示:

在跳轉頁面的時候,在js代碼中的操作如下,在標簽中使用<router-link>標簽

this.$router.push({
    name: 'routePage',
    query/params: {
        routeParams: params
    }
})    

 需要注意的是,實用params去傳值的時候,在頁面刷新時,參數會消失,用query則不會有這個問題。

 這樣使用起來很方便,但url會變得很長,而且如果不是使用路由跳轉的界面無法使用。取值方式分別為:this.$route.params.paramName和this.$route.query.paramName

   注:使用params傳值,也可以做到頁面刷新,參數不丟失,在命名路由時這樣設置:

{  
      path: '/OrderDetail/:orderId/:type',  
      name: 'OrderDetail',  
      component: OrderDetail,  
      meta: {  
        title: '訂單詳情',  
        needAuth: true  
      }  
}  

使用時:

this.$router.push({name: 'OrderDetail', params: {orderId: id, type: 'buy'}})

這種方式會把路由導航到 /OrderDetail/22aead11a99c4c91aa2169ac17d0ddb5/booking 路徑

參考:http://router.vuejs.org/zh-cn/essentials/named-routes.html

 

二、通過$parent,$chlidren等方法調取用層級關系的組件內的數據和方法

  通過下面的方法調用:

this.$parent.$data.id  //獲取父元素data中的id
this.$children.$data.id  //獲取父元素data中的id

這樣用起來比較靈活,但是容易造成代碼耦合性太強,導致維護困難

 

三、采用eventBus.js傳值---兄弟組件間的傳值

eventBus.js

import Vue from 'Vue'

export default new Vue()

App.vue

<template>
  <div id="app">
    <secondChild></secondChild>
    <firstChild></firstChild>
  </div>
</template>

<script>
import FirstChild from './components/FirstChild'
import SecondChild from './components/SecondChild'

export default {
  name: 'app',
  components: {
    FirstChild,
    SecondChild,
  }
}
</script>

FirstChild.vue

<template>
  <div class="firstChild">
    <input type="text" placeholder="請輸入文字" v-model="message">
    <button @click="showMessage">向組件傳值</button>
    <br>
    <span>{{message}}</span>
  </div>
</template>
<script>
  import bus from '../assets/eventBus';
  export default{
    name: 'firstChild',
    data () {
      return {
        message: '你好'
      }
    },
    methods: {
      showMessage () {
       alert(this.message)
        bus.$emit('userDefinedEvent', this.message);//傳值
      }
    }
  }
</script>

SecondChild.vue

<template>
    <div id="SecondChild">
        <h1>{{message}}</h1>
    </div>
</template>
<script>
    import bus from '../assets/eventBus';
    export default{
        name:'SecondChild',
        data(){
            return {
                message: ''
            }
        },
        mounted(){
            var self = this;
            bus.$on('userDefinedEvent',function(message){
                self.message = message;//接值
            });
        }
    }

 

四、通過localStorage或者sessionStorage來存儲數據(參考:https://blog.csdn.net/qq_32786873/article/details/70853819)

setItem存儲value
用途:將value存儲到key字段
用法:.setItem( key, value)
代碼示例:

sessionStorage.setItem("key", "value");  localStorage.setItem("site", "js8.in");

 


getItem獲取value
用途:獲取指定key本地存儲的值
用法:.getItem(key)
代碼示例:

var value = sessionStorage.getItem("key");  var site = localStorage.getItem("site");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM