欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          vue組件怎么傳值

          傳值方法:1、利用props實現(xiàn)父傳子;2、子傳父,需要自定義事件,在子組件中用“this.$emit(‘事件名’)”觸發(fā),而父中用“@事件名”監(jiān)聽;3、兄弟間,通過公有父元素作為橋接,結(jié)合父子props傳參、子父自定義事件;4、用路由傳值;5、用$ref傳值;6、用依賴注入傳給后代子孫曾孫;7、利用$attrs;8、借助$listeners中間事件;9、用$parent傳等。

          vue組件怎么傳值

          本教程操作環(huán)境:windows7系統(tǒng)、vue3版,DELL G3電腦。

          本篇文章帶大家聊聊vue組件傳值的10種方式,常用的也有五六種,先上一張總結(jié)圖:

          vue組件怎么傳值

          1、父組件傳給子組件

          在子組件里定義一個props,即props:[‘msg’],msg可以是對象也可以是基本數(shù)據(jù)類型

          如果你想定義一個默認值,即 props:{msg: {type: String, default: ‘hello world’}},
          若默認值是對象類型:props: { msg: { type: Object, default: () => { return { name: ‘dan_seek’ } } }}

          需要注意的是這種傳值是單向的,你無法改變父組件的值(當然引用類型例外);而且如果直接修改props的值會報一個警告。

          推薦的寫法是在data()里重新定義一個變量(見Children.vue),并把props賦值給它,當然計算屬性也行。

          Children.vue

          <template>     <section>         父組件傳過來的消息是:{{myMsg}}     </section> </template>  <script>     export default {         name: "Children",         components: {},         props:['msg'],         data() {             return {                 myMsg:this.msg             }         },         methods: {}     } </script>
          登錄后復制

          Parent.vue

          <template>   <div class="parent">     <Children :msg="message"></Children>   </div> </template>  <script> import Children from '../components/Children'  export default {   name: 'Parent',   components: {       Children   },   data() {       return {           message:'hello world' } }, } </script>
          登錄后復制

          2、子組件傳給父組件

          這里需要使用自定義事件,在子組件中使用this.$emit(‘myEvent’) 觸發(fā),然后在父組件中使用@myEvent監(jiān)聽

          Children.vue

          <template>     <div class="parent">         這里是計數(shù):{{parentNum}}         <Children-Com @addNum="getNum"></Children-Com>     </div> </template>  <script>     import ChildrenCom from '../components/Children'      export default {         name: 'Parent',         components: {             ChildrenCom         },         data() {             return {                 parentNum: 0             }         },         methods:{             // childNum是由子組件傳入的             getNum(childNum){                 this.parentNum = childNum             }         }     } </script>
          登錄后復制

          Parent.vue

          <template>     <div class="parent">         這里是計數(shù):{{parentNum}}         <Children-Com @addNum="getNum"></Children-Com>     </div></template><script>     import ChildrenCom from '../components/Children'      export default {         name: 'Parent',         components: {             ChildrenCom        },         data() {             return {                 parentNum: 0             }         },         methods:{             // childNum是由子組件傳入的             getNum(childNum){                 this.parentNum = childNum            }         }     }</script>
          登錄后復制

          3、兄弟組件間傳值

          運用自定義事件emit的觸發(fā)和監(jiān)聽能力,定義一個公共的事件總線eventBus,通過它作為中間橋梁,我們就可以傳值給任意組件了。而且通過eventBus的使用,可以加深emit的理解。

          EventBus.js

          import Vue from 'vue' export default new Vue()
          登錄后復制

          Children1.vue

          <template>     <section>         <div @click="pushMsg">push message</div>         <br>     </section> </template>  <script>     import eventBus from './EventBus'     export default {         name: "Children1",         components: {},         data() {             return {                 childNum:0             }         },         methods: {             pushMsg(){             	// 通過事件總線發(fā)送消息                 eventBus.$emit('pushMsg',this.childNum++)             }         }     } </script>
          登錄后復制

          Children2.vue

          <template>     <section>         children1傳過來的消息:{{msg}}     </section> </template>  <script>     import eventBus from './EventBus'      export default {         name: "Children2",         components: {},         data() {             return {                 msg: ''             }         },         mounted() {         	// 通過事件總線監(jiān)聽消息             eventBus.$on('pushMsg', (children1Msg) => {                 this.msg = children1Msg             })         }     } </script>
          登錄后復制

          Parent.vue

          <template>     <div class="parent">         <Children1></Children1>         <Children2></Children2>     </div> </template>  <script>     import Children1 from '../components/Children1'     import Children2 from '../components/Children2'      export default {         name: 'Parent',         components: {             Children1,             Children2         },         data() {             return {             }         },         methods:{         }     } </script>
          登錄后復制

          github上還有一個開源vue-bus庫,可以參考下: https://github.com/yangmingshan/vue-bus#readme

          4、路由間傳值

          i.使用問號傳值

          A頁面跳轉(zhuǎn)B頁面時使用 this.$router.push(‘/B?name=danseek’)

          B頁面可以使用 this.$route.query.name 來獲取A頁面?zhèn)鬟^來的值

          上面要注意router和route的區(qū)別

          ii.使用冒號傳值

          配置如下路由:

          {     path: '/b/:name',     name: 'b',     component: () => import( '../views/B.vue')   },
          登錄后復制

          在B頁面可以通過 this.$route.params.name 來獲取路由傳入的name的值

          iii.使用父子組件傳值

          由于router-view本身也是一個組件,所以我們也可以使用父子組件傳值方式傳值,然后在對應的子頁面里加上props,因為type更新后沒有刷新路由,所以不能直接在子頁面的mounted鉤子里直接獲取最新type的值,而要使用watch。

          <router-view :type="type"></router-view>
          登錄后復制

          // 子頁面 ...... props: ['type'] ...... watch: {             type(){                 // console.log("在這個方法可以時刻獲取最新的數(shù)據(jù):type=",this.type)             },         },
          登錄后復制

          5、使用$ref傳值

          通過$ref的能力,給子組件定義一個ID,父組件通過這個ID可以直接訪問子組件里面的方法和屬性

          首先定義一個子組件Children.vue

          <template>     <section>         傳過來的消息:{{msg}}     </section> </template>  <script>     export default {         name: "Children",         components: {},         data() {             return {                 msg: '',                 desc:'The use of ref'             }         },         methods:{             // 父組件可以調(diào)用這個方法傳入msg             updateMsg(msg){                 this.msg = msg             }         },     } </script>
          登錄后復制

          然后在父組件Parent.vue中引用Children.vue,并定義ref屬性

          <template>     <div class="parent">         <!-- 給子組件設置一個ID ref="children" -->         <Children ref="children"></Children>         <div @click="pushMsg">push message</div>     </div> </template>  <script>     import Children from '../components/Children'      export default {         name: 'parent',         components: {             Children,         },         methods:{             pushMsg(){                 // 通過這個ID可以訪問子組件的方法                 this.$refs.children.updateMsg('Have you received the clothes?')                 // 也可以訪問子組件的屬性                 console.log('children props:',this.$refs.children.desc)             }         },     } </script>
          登錄后復制

          6、使用依賴注入傳給后代子孫曾孫

          假設父組件有一個方法 getName(),需要把它提供給所有的后代

          provide: function () {   return {     getName: this.getName()   } }
          登錄后復制

          provide 選項允許我們指定我們想要提供給后代組件的數(shù)據(jù)/方法

          然后在任何后代組件里,我們都可以使用 inject 來給當前實例注入父組件的數(shù)據(jù)/方法:

          inject: ['getName']
          登錄后復制

          Parent.vue

          <template>     <div class="parent">         <Children></Children>     </div> </template>  <script>     import Children from '../components/Children'      export default {         name: 'Parent',         components: {             Children,         },         data() {             return {                 name:'dan_seek'             }         },         provide: function () {             return {                 getName: this.name             }         },     } </script>
          登錄后復制

          Children.vue

          <template>     <section>         父組件傳入的值:{{getName}}     </section> </template>  <script>     export default {         name: "Children",         components: {},         data() {             return {             }         },         inject: ['getName'],     } </script>
          登錄后復制

          7、祖?zhèn)鲗O $attrs

          正常情況下需要借助父親的props作為中間過渡,但是這樣在父親組件就會多了一些跟父組件業(yè)務無關的屬性,耦合度高,借助$attrs可以簡化些,而且祖跟孫都無需做修改

          GrandParent.vue

          <template>     <section>         <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent>     </section> </template>  <script>     import Parent from './Parent'     export default {         name: "GrandParent",         components: {           Parent         },         data() {             return {}         },         methods: {           sayKnow(val){             console.log(val)           }         },         mounted() {         }     } </script>
          登錄后復制

          Parent.vue

          <template>   <section>     <p>父組件收到</p>     <p>祖父的名字:{{name}}</p>     <children v-bind="$attrs" v-on="$listeners"></children>   </section> </template>  <script>   import Children from './Children'    export default {     name: "Parent",     components: {       Children     },     // 父組件接收了name,所以name值是不會傳到子組件的     props:['name'],     data() {       return {}     },     methods: {},     mounted() {     }   } </script>
          登錄后復制

          Children.vue

          <template>   <section>     <p>子組件收到</p>     <p>祖父的名字:{{name}}</p>     <p>祖父的性別:{{sex}}</p>     <p>祖父的年齡:{{age}}</p>     <p>祖父的愛好:{{hobby}}</p>      <button @click="sayKnow">我知道啦</button>   </section> </template>  <script>   export default {     name: "Children",     components: {},     // 由于父組件已經(jīng)接收了name屬性,所以name不會傳到子組件了     props:['sex','age','hobby','name'],     data() {       return {}     },     methods: {       sayKnow(){         this.$emit('sayKnow','我知道啦')       }     },     mounted() {     }   } </script>
          登錄后復制

          顯示結(jié)果

          父組件收到 祖父的名字:grandParent 子組件收到 祖父的名字: 祖父的性別:男 祖父的年齡:88 祖父的愛好:code
          登錄后復制

          8、孫傳祖

          借助$listeners中間事件,孫可以方便的通知祖,代碼示例見7

          9、$parent

          通過parent可以獲父組件實例,然后通過這個實例就可以訪問父組件的屬性和方法,它還有一個兄弟root,可以獲取根組件實例。

          語法:

          // 獲父組件的數(shù)據(jù) this.$parent.foo  // 寫入父組件的數(shù)據(jù) this.$parent.foo = 2  // 訪問父組件的計算屬性 this.$parent.bar  // 調(diào)用父組件的方法 this.$parent.baz()
          登錄后復制

          于是,在子組件傳給父組件例子中,可以使用this.$parent.getNum(100)傳值給父組件。

          10、sessionStorage傳值

          sessionStorage 是瀏覽器的全局對象,存在它里面的數(shù)據(jù)會在頁面關閉時清除 。運用這個特性,我們可以在所有頁面共享一份數(shù)據(jù)。

          語法:

          // 保存數(shù)據(jù)到 sessionStorage sessionStorage.setItem('key', 'value');  // 從 sessionStorage 獲取數(shù)據(jù) let data = sessionStorage.getItem('key');  // 從 sessionStorage 刪除保存的數(shù)據(jù) sessionStorage.removeItem('key');  // 從 sessionStorage 刪除所有保存的數(shù)據(jù) sessionStorage.clear();
          登錄后復制

          注意:里面存的是鍵值對,只能是字符串類型,如果要存對象的話,需要使用 let objStr = JSON.stringify(obj) 轉(zhuǎn)成字符串然后再存儲(使用的時候 let obj = JSON.parse(objStr) 解析為對象)。

          這樣存對象是不是很麻煩呢,推薦一個庫 good-storage ,它封裝了sessionStorage ,可以直接用它的API存對象

          // localStorage  storage.set(key,val)   storage.get(key, def)    // sessionStorage  storage.session.set(key, val)  storage.session.get(key, val)
          登錄后復制

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號