溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue props 單項數(shù)據(jù)流實例分享

發(fā)布時間:2020-09-13 15:31:44 來源:腳本之家 閱讀:147 作者:shysun 欄目:web開發(fā)

vue props 單項數(shù)據(jù)流實例分享

父組件傳遞動態(tài)值showStoreList,子組件通過props接收,但是如果在子組件中直接使用并修改這個值會報錯;

因為父級的更新會傳遞給子組件,但是反過來則不行;

這種情況下,可以使用computed或watch來獲取props中的值

vue props 單項數(shù)據(jù)流實例分享

以上實例不難,下面由億速云小編整理的補充內(nèi)容:

Vue2.x通過props傳遞數(shù)據(jù)是單向的了,也就是父組件數(shù)據(jù)變化時會傳遞給子組件,但是反過來不行。

業(yè)務(wù)中會經(jīng)常遇到兩種需要改變prop的情況,

一種是父組件傳遞初始值進來,子組件將它作為初始值保存起來,在自己的作用域下可以隨意使用和修改。這種情況可以在組件data內(nèi)再聲明一個數(shù)據(jù),引用父組件的prop,示例代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./vue.js"></script>
</head>
<body>
  <div id="app">
    <my-component :init-count="1"></my-component>
  </div>
  <script>
    Vue.component('my-component',{
      props:['init-count'],
      template:'<div>{{count}}</div>',
      data:function(){
        return {
          count:this.initCount
        }
      }
    })
    new Vue({
      el:'#app',
    })
  </script>
</body>
</html>

組件中聲明了數(shù)據(jù)count,它在組件初始化時會獲取來自父組件的initCount,之后就與之無關(guān)了,只用維護count,這樣就可以避免直接操作initCount。

另一種情況就是prop作為需要被轉(zhuǎn)變的原始值傳入。這種情況用計算屬性就可以了,示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./vue.js"></script>
</head>
<body>
  <div id="app">
    <mynew-component :width="100"></mynew-component>
  </div>
  <script>
    Vue.component('mynew-component',{
      props:['width'],
      template:'<div :>組件內(nèi)容</div>',
      computed:{
        style:function(){
          return {
            width:this.width+'px',
            background:'lightgray',
            textAlign:'center'
          }
        }
      }
    })
    new Vue({
      el:'#app',
    })
  </script>
</body>
</html>

注意:

在JavaScript中對象和數(shù)組是引用類型,指向同一個內(nèi)存空間,所以props是對象和數(shù)組時,在子組件內(nèi)改變是會影響父組件的。

//如此解決引用傳遞

1:var newObject = jQuery.extend(true, {}, oldObject);

2:var obj={};

obj=JSON.parse(JSON.stringify(oldObject));

以上就是本次介紹地全部相關(guān)知識點,感謝大家的學(xué)習(xí)和對億速云的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI