新聞中心
Vue項(xiàng)目中經(jīng)常使用到組件之間的數(shù)值傳遞,實(shí)現(xiàn)的方法很多,但是原理上基本大同小異。

實(shí)現(xiàn)思路:
父 向 子 組件傳值:使用 props 屬性。( props 是property[屬性] 的復(fù)數(shù)簡寫 )
子 向 父 組件傳值:使用自定義事件。
一、父子組件單向傳值
1.1、父向子傳值
父向子組件傳值,子組件接收到數(shù)據(jù)之后,保存到自己的變量中。
- //父組件寫法
- //子組件定義以及數(shù)據(jù)
- components:{
- cld:{
- template:'#child',
- props:{
- numP:Number
- },
- }
- }
- //子組件內(nèi)容
- {{ numP }}
props 用于接收父組件傳過來的值,props 的寫法有很多種,具體如:
- //方式1 : 直接接收數(shù)據(jù)
- props: [ 'numP' ]
- //方式2: 加類型限制
- props: [
- numP: Number
- ]
- //方式3:添加默認(rèn)值
- props: [
- numP: {
- type:Number,
- default:0
- }
- ]
- //方式4:是否必須值限制
- props: [
- numP: {
- type:Number,
- default:0,
- require:true //添加必須值,不傳此值會報錯
- }
- ]
- //方式5:采用對象形式
- props: {
- numP: {
- type:Number,
- default:0,
- }
- }
1.2、子向父傳值
子向父組件傳值,主要通過自定義事件進(jìn)行傳值,具體實(shí)例如下:
- // 父組件內(nèi)容
- 子組件獲取到的數(shù)據(jù){{getNum}}
- //父組件方法
- methods:{
- getNumC(data){
- this.getNum = data //接收子組件傳的數(shù)據(jù)
- }
- },
- //子組件定義
- components:{
- cld:{
- template:'#child',
- data(){
- return{
- numC:1314 //子組件數(shù)據(jù)定義
- }
- },
- mounted(){
- this.$emit( 'accept' , this.numC ) // 觸發(fā)自定義事件
- }
- }
- },
二、父子組件數(shù)據(jù)雙向綁定
Vue 的數(shù)據(jù)都是單向流動的,而且 vue 中從來就沒有任何的雙向綁定,v-model 實(shí)現(xiàn)的雙向綁定只是語法糖而已。
方式1:利用 watch 實(shí)現(xiàn)父子組件的數(shù)據(jù)雙向綁定,具體實(shí)例如下:
- 數(shù)據(jù)
{{num}}
- //子組件內(nèi)容
- 數(shù)據(jù)
{{childNum}}- const app = new Vue({
- el:'#app',
- data:{
- num:'520',
- },
- methods:{
- getNumC(data){
- this.num = data
- }
- },
- components:{
- cld:{
- template:'#child',
- props:{
- numb:String
- },
- data(){
- return{
- childNum:0,
- }
- },
- watch:{
- numb:function(){
- this.childNum = this.numb
- },
- childNum:function(){
- this.$emit('accept',this.childNum)
- }
- },
- mounted(){
- this.childNum = this.numb
- }
- }
- }
- })
方式2:.sync 修飾符實(shí)現(xiàn)雙向綁定
在vue 1.x 中的 .sync 修飾符所提供的功能。當(dāng)一個子組件改變了一個帶 .sync 的 prop 的值時,這個變化也會同步到父組件中所綁定的值。這很方便,但也會導(dǎo)致問題,因?yàn)樗茐牧藛蜗驍?shù)據(jù)流。(數(shù)據(jù)自上而下流,事件自下而上走)
- //會擴(kuò)展為:
bar = val”/>
當(dāng)組件需要更新 numb 的值時,需要觸發(fā)更新事件:
- this.$emit("update:numb", newValue );
使用具體實(shí)例如下:
- // 父組件
- //子組件
- props: ['foo'],
- data() {
- return {
- newFoo: this.foo;
- }
- },
- methods:{
- add:function(){
- this.newMsg=10;
- this.$emit('update:foo',this.newFoo);
- }
- }
分享文章:前端框架Vue—父子組件數(shù)據(jù)雙向綁定
文章位置:http://m.fisionsoft.com.cn/article/cohshcj.html


咨詢
建站咨詢
