溫馨提示×

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

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

vuejs中傳遞數(shù)據(jù)有哪些方法

發(fā)布時(shí)間:2021-09-26 09:29:34 來源:億速云 閱讀:173 作者:小新 欄目:web開發(fā)

小編給大家分享一下vuejs中傳遞數(shù)據(jù)有哪些方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

傳遞方法:1、父組件中利用“props”向子組件傳遞數(shù)據(jù);2、子組件利用“this.$emit(“事件”)”向父組件傳遞數(shù)據(jù);3、兄弟組件間利用公共文件傳遞數(shù)據(jù);4、父子組件間利用“ref/refs”傳遞數(shù)據(jù);5、使用Vuex傳遞數(shù)據(jù)等等。

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

一.父?jìng)髯觽鬟f

(1)在父組件的子組件標(biāo)簽上綁定一個(gè)屬性,掛載要傳輸?shù)淖兞?/p>

(2)在子組件中通過props來接受數(shù)據(jù),props可以是數(shù)組也可以是對(duì)象,接受的數(shù)據(jù)可以直接使用 props: [“屬性 名”] props:{屬性名:數(shù)據(jù)類型}

代碼示例:

//父組件
<template>
  <p>
    <i>父組件</i>
    <!--頁面使用-->
    <son :data='name'></son> 
  </p>
</template>

<script>
import son from "./son.vue";//導(dǎo)入父組件
export default {
  components: { son },//注冊(cè)組件
  name: "父組件",
  data() {
    return {
      name: "Frazier", //父組件定義變量
    };
  },
};
</script>
//子組件
<template>
  <p>{{data}}</p>
</template>

<script>
export default {
components: { },
  name: '子組件',
  props:["data"],
};
</script>

二.子傳父?jìng)鬟f

(1)在父組件的子組件標(biāo)簽上自定義一個(gè)事件,然后調(diào)用需要的方法
(2)在子組件的方法中通過 this.$emit(“事件”)來觸發(fā)在父組件中定義的事件,數(shù)據(jù)是以參數(shù)的形式進(jìn)行傳遞的

代碼示例:

//父組件
<template>
  <p>
    <i>父組件</i>
    <!--頁面使用-->
    <son @lcclick="lcclick"></son>//自定義一個(gè)事件
  </p>
</template>

<script>
import son from "./son.vue"; //導(dǎo)入父組件
export default {
  components: { son }, //注冊(cè)組件
  name: "父組件",
  data() {
    return {};
  },
  methods: {
    lcclick(){
      alert('子傳父')
    }
  },
};
</script>
//子組件
<template>
  <p>
    <button @click="lcalter">點(diǎn)我</button>
  </p>
</template>

<script>
export default {
components: { },
  name: '子組件',
  methods: {
    lcalter(){
      this.$emit('lcclick')//通過emit來觸發(fā)事件
    }
  },
};
</script>

三.兄弟組件通信(bus總線)

(1)在src中新建一個(gè)Bus.js的文件,然后導(dǎo)出一個(gè)空的vue實(shí)例
(2)在傳輸數(shù)據(jù)的一方引入Bus.js 然后通過Bus. e m i t ( “ 事 件 名 ” , " 參 數(shù) " ) 來 來 派 發(fā) 事 件 , 數(shù) 據(jù) 是 以 emit(“事件名”,"參數(shù)")來來派發(fā)事件,數(shù)據(jù)是以 emit(“事件名”,"參數(shù)")來來派發(fā)事件,數(shù)據(jù)是以emit()的參 數(shù)形式來傳遞
(3)在接受的數(shù)據(jù)的一方 引入 Bus.js 然后通過 Bus.$on(“事件名”,(data)=>{data是接受的數(shù)據(jù)})

圖片示例:

vuejs中傳遞數(shù)據(jù)有哪些方法

vuejs中傳遞數(shù)據(jù)有哪些方法

vuejs中傳遞數(shù)據(jù)有哪些方法

四.ref/refs(父子組件通信)

(1)ref 如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實(shí)例,
(2)可以通過實(shí)例直接調(diào)用組件的方法或訪問數(shù)據(jù)。也算是子組件向父組件傳值的一種

代碼示例:

//父組件
<template>
  <p>
    <button @click="sayHello">sayHello</button>
    <child ref="childForRef"></child>
  </p>
</template>
<script>
import child from './child.vue'
  export default {
    components: { child },
    data () {
      return {
        childForRef: null,
      }
    },
    mounted() {
      this.childForRef = this.$refs.childForRef;
      console.log(this.childForRef.name);
    },
    methods: {
      sayHello() {
        this.childForRef.sayHello()
      }
    }
  }
</script>
//子組件
<template>
  <p>child 的內(nèi)容</p>
</template>
<script>
export default {
  data () {
    return {
      name: '我是 child',
    }
  },
  methods: {
    sayHello () {
      console.log('hello');
      alert('hello');
    }
  }
}
</script>

五.Vuex通信

組件通過 dispatch 到 actions,actions 是異步操作,再 actions中通過 commit 到 mutations,mutations 再通過邏輯操作改變 state,從而同步到組件,更新其數(shù)據(jù)狀態(tài)

代碼示例:

//父組件
template>
  <p id="app">
    <ChildA/>
    <ChildB/>
  </p>
</template>
<script>
  import ChildA from './ChildA' // 導(dǎo)入A組件
  import ChildB from './ChildB' // 導(dǎo)入B組件
  export default {
    components: {ChildA, ChildB} // 注冊(cè)組件
  }
</script>
//子組件A
<template>
 <p id="childA">
   <h2>我是A組件</h2>
   <button @click="transform">點(diǎn)我讓B組件接收到數(shù)據(jù)</button>
   <p>因?yàn)辄c(diǎn)了B,所以信息發(fā)生了變化:{{BMessage}}</p>
 </p>
</template>
<script>
 export default {
   data() {
     return {
       AMessage: 'Hello,B組件,我是A組件'
     }
   },
   computed: {
     BMessage() {
       // 這里存儲(chǔ)從store里獲取的B組件的數(shù)據(jù)
       return this.$store.state.BMsg
     }
   },
   methods: {
     transform() {
       // 觸發(fā)receiveAMsg,將A組件的數(shù)據(jù)存放到store里去
       this.$store.commit('receiveAMsg', {
         AMsg: this.AMessage
       })
     }
   }
 }
</script>
//子組件B
<template>
 <p id="childB">
   <h2>我是B組件</h2>
   <button @click="transform">點(diǎn)我讓A組件接收到數(shù)據(jù)</button>
   <p>點(diǎn)了A,我的信息發(fā)生了變化:{{AMessage}}</p>
 </p>
</template>

<script>
 export default {
   data() {
     return {
       BMessage: 'Hello,A組件,我是B組件'
     }
   },
   computed: {
     AMessage() {
       // 這里存儲(chǔ)從store里獲取的A組件的數(shù)據(jù)
       return this.$store.state.AMsg
     }
   },
   methods: {
     transform() {
       // 觸發(fā)receiveBMsg,將B組件的數(shù)據(jù)存放到store里去
       this.$store.commit('receiveBMsg', {
         BMsg: this.BMessage
       })
     }
   }
 }
</script>
//vuex
import Vue from 'vue'
 import Vuex from 'vuex'
 Vue.use(Vuex)
 const state = {
   AMsg: '',
   BMsg: ''
 }
 
 const mutations = {
   receiveAMsg(state, payload) {
     // 將A組件的數(shù)據(jù)存放于state
     state.AMsg = payload.AMsg
   },
   receiveBMsg(state, payload) {
     // 將B組件的數(shù)據(jù)存放于state
     state.BMsg = payload.BMsg
   }
 }
 
 export default new Vuex.Store({
   state,
   mutations
 })

六.$parent

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

代碼示例:

// 獲父組件的數(shù)據(jù)
this.$parent.foo

// 寫入父組件的數(shù)據(jù)
this.$parent.foo = 2

// 訪問父組件的計(jì)算屬性
this.$parent.bar

// 調(diào)用父組件的方法
this.$parent.baz()

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

七.sessionStorage傳值

sessionStorage 是瀏覽器的全局對(duì)象,存在它里面的數(shù)據(jù)會(huì)在頁面關(guān)閉時(shí)清除 。運(yùn)用這個(gè)特性,我們可以在所有頁面共享一份數(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();

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

推薦一個(gè)庫 good-storage ,它封裝了sessionStorage ,可以直接用它的API存對(duì)象

//localStorage
 storage.set(key,val) 
 storage.get(key, def)
//sessionStorage
 storage.session.set(key, val)
 storage.session.get(key, val)

八.路由傳值

使用問號(hào)傳值

A頁面跳轉(zhuǎn)B頁面時(shí)使用 this. r o u t e r . p u s h ( ' / B ? n a m e = d a n s e e k ' ) B 頁 面 可 以 使 用 t h i s . router.push('/B?name=danseek') B頁面可以使用 this. router.push('/B?name=danseek')B頁面可以使用this.route.query.name 來獲取A頁面?zhèn)鬟^來的值

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

使用冒號(hào)傳值

配置如下路由:

{
    path: '/b/:name',
    name: 'b',
    component: () => import( '../views/B.vue')
 },

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

使用父子組件傳值
由于router-view本身也是一個(gè)組件,所以我們也可以使用父子組件傳值方式傳值,然后在對(duì)應(yīng)的子頁面里加上props,因?yàn)閠ype更新后沒有刷新路由,所以不能直接在子頁面的mounted鉤子里直接獲取最新type的值,而要使用watch

<router-view :type="type"></router-view>

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

九.祖?zhèn)鲗O $attrs

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

祖組件:

<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>

父組件

<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值是不會(huì)傳到子組件的
    props:['name'],
    data() {
      return {}
    },
    methods: {},
    mounted() {
    }
  }
</script>

子組件

<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不會(huì)傳到子組件了
    props:['sex','age','hobby','name'],
    data() {
      return {}
    },
    methods: {
      sayKnow(){
        this.$emit('sayKnow','我知道啦')
      }
    },
    mounted() {
    }
  }
</script>

十.孫傳祖使用$listeners

文字內(nèi)容同第九個(gè)

祖組件

<template>
  <p id="app">
    <children-one @eventOne="eventOne"></children-one>
    {{ msg }}
  </p>
</template>
<script>
import ChildrenOne from '../src/components/children.vue'
export default {
  name: 'App',
  components: {
    ChildrenOne,
  },
  data() {
    return {
      msg: ''
    }
  },
  methods: {
    eventOne(value) {
      this.msg = value
    }
  }
}
</script>

父組件

<template>
  <p>
    <children-two v-on="$listeners"></children-two>
  </p>
</template>

<script>
import ChildrenTwo from './childrenTwo.vue'

export default {
  name: 'childrenOne',
  components: {
    ChildrenTwo
  }
}
</script>

子組件

<template>
  <p>
    <button @click="setMsg">點(diǎn)擊傳給祖父</button>
  </p>
</template>

<script>
export default {
  name: 'children',
  methods: {
    setMsg() {
      this.$emit('eventOne', '123')
    }
  }
}
</script>

十一.promise傳參

promise 中 resolve 如何傳遞多個(gè)參數(shù)

//類似與這樣使用,但實(shí)際上后面兩個(gè)參數(shù)無法獲取
promise = new Promise((resolve,reject)=>{
    let a = 1
    let b = 2
    let c = 3
    resolve(a,b,c) 
})
promise.then((a,b,c)=>{
    console.log(a,b,c)
})

resolve() 只能接受并處理一個(gè)參數(shù),多余的參數(shù)會(huì)被忽略掉。

如果想多個(gè)用數(shù)組,或者對(duì)象方式。。

數(shù)組

promise = new Promise((resolve,reject)=>{
    resolve([1,2,3]) 
})
promise.then((arr)=>{
    console.log(arr[0],arr[1],arr[2])
})

對(duì)象

promise = new Promise((resolve,reject)=>{
    resolve({a:1,b:2,c:3}) 
})
promise.then(obj=>{
    console.log(obj.a,obj.b,obj.c)
})

十二.全局變量

定義一個(gè)全局變量,在有值的組件直接賦值,在需要的組件內(nèi)直接使用就可以了。

以上是“vuejs中傳遞數(shù)據(jù)有哪些方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

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

vue
AI