2-4 vue props數(shù)據(jù)一定是單向的

props數(shù)據(jù)一定是單向的

  • <strong>prop默認是單向綁定</strong>

  • 當父組件的屬性變化時,將傳導(dǎo)給子組件,但是反過來不會。這是為了防止子組件無意修改了父組件的狀態(tài)。

  • 案例驗證:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title></title>
</head>
<body>
   <div id="app">
       <table>
           <tr>
               <th colspan="3">父組件</th>
           </tr>
           <tr>
               <td>國家</td>
               <td>{{country}}</td>
               <td><input type="text" v-model="country"></td>
           </tr>
           <tr>
               <td>地區(qū)</td>
               <td>{{area}}</td>
               <td><input type="text" v-model="area"></td>
           </tr>
       </table>
       <br>
       <my-child :child-country="country" :child-area="area"></my-child>
   </div>
   <template id="child">
       <table>
           <tr>
               <th colspan="3">子組件</th>
           </tr>
           <tr>
               <td>國家</td>
               <td>{{ childCountry }}</td>
               <td><input type="text" v-model="childCountry"></td>
           </tr>
           <tr>
               <td>地區(qū)</td>
               <td>{{ childArea }}</td>
               <td><input type="text" v-model="childArea"></td>
           </tr>
       </table>
   </template>
<script src="js/vue.js"></script>
<script>
   new Vue({
       el: '#app',
       data:{
           country: '中國',
           area: '亞洲'
       },
       components:{
           'my-child': {
               template: '#child',
               props: [ "childCountry", "childArea"]
           }
       }
   })
</script>
</body>
</html>
  • 運行結(jié)果:
vueb5.png
  • 結(jié)論

在vuejs2.0中,任何試圖在組件內(nèi)修改通過props傳入的父組件數(shù)據(jù)都被認為是anti-pattern的。


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容