溫馨提示×

溫馨提示×

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

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

Vue中組件之間數(shù)據(jù)的傳遞的示例代碼

發(fā)布時間:2020-09-27 04:23:00 來源:腳本之家 閱讀:162 作者:Always明媚 欄目:web開發(fā)

Vue中組件的作用域是隔離的,父組件中的數(shù)值子組件看不到!也就是說,用angular作比喻,組件的scope天生是scope:()的!
如果父組件需要往子組件中傳數(shù)據(jù),此時應該使用標簽屬性:

<div id="app">
   <my-compo c="886"></my-compo>
</div>

子組件中,用props聲明這個值即可。并且在template里面可以直接使用{{c}}來獲得這個屬性,而不需要寫為{{this.props.c}}

import Vue from "vue";

const MyCompo = Vue.extend({
  template : `
    <div>
      <h2>我是MyCompo組件,我的a值是{{a}}</h2>
      <h2>子組件c:{{c}}</h2>
      <input type="button" value="+++" v-on:click="add"/>
    </div>
  `,
  props : ["c"],
  data : function(){
    return {
      a : 1, 
      b : 2
    }
  },
  methods : {
    add : function(){
      this.a ++;
    }
  }
});

export default MyCompo;

如果父組件中要傳一個動態(tài)的值(就是父組件的data,不是死數(shù)),此時要用v-bind:來傳遞。
v-bind指令表示動態(tài)屬性。

<div id="app">
   <my-compo v-bind:c="c"></my-compo>
</div>

此時我們研究,子組件改變了這個值,父組件的值變不變。答:默認情況下不變!

<my-compo v-bind:c="c"></my-compo>

import Vue from "vue";

const MyCompo = Vue.extend({
  template : `
    <div>
      <h2>我是MyCompo組件,我的a值是{{a}},我的c值是:{{c}}</h2>
      <input type="button" value="+++" v-on:click="add"/>

    </div>
  `,
  props : ["c"],
  methods : {
    add : function(){
      this.c ++;
    }
  }
});

export default MyCompo;

子組件的c值變化了,但是外面不變!

也就是說,默認情況下,父組件中的屬性值如果傳給兒子,子組件改變這個值,僅僅改變子組件中的值,父組件中的值不變。

如果非要讓子組件能夠改變父組件中的值,要加sync修飾符:

<my-compo v-bind:c.sync="c"></my-compo>

上面的c屬性是一個基本類型值常數(shù)3。此時我們試試引用類型值。

父組件中增加d屬性,值是json。

import Vue from "vue";
import MyCompo from "./components/MyCompo.js";

new Vue({
  el : "#app",
  data : {
    c : 333,
    d : {
      v : 8888
    }
  },
  components : {
    "my-compo" : MyCompo
  }
});

傳給子組件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue學習</title>
</head>
<body>
  <div id="app">
    <h2>我是父親,我的c: {{c}} ,我的d:{{d | json}}</h2>
     <my-compo v-bind:c.sync="c" v-bind:d="d"></my-compo>
  </div>

  <script type="text/javascript" src="public/bundle.js"></script>
</body>
</html>

子組件改變d的時候,父親也變了?。?!雖然我們沒加.sync。

總結:

Vue中基本類型值默認單向傳遞,雙向加sync。

引用類型值,默認雙向傳遞。

小tip,v-bind的縮寫語法就是冒號。

Vue中組件之間數(shù)據(jù)的傳遞的示例代碼

屬性可以驗證類型、必填等等。

props : {
    "c" : null,
    "d" : null,
    "e" : {
      type : Number,
      required : true
    }
},

Vue中組件之間數(shù)據(jù)的傳遞的示例代碼

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

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

AI