亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue中如何讓子組件修改父組件數(shù)據(jù)

 更新時間:2018年06月14日 10:48:03   作者:水痕01  
這篇文章主要介紹了vue中子組件修改父組件數(shù)據(jù)的相關(guān)資料,文中介紹了vue中watch的認識,關(guān)于子組件修改父組件屬性認識,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下

一、關(guān)于vue中watch的認識

我們要監(jiān)聽一個屬性的的變化就使用watch一般是父組件傳遞給子組件的時候

•1、常見的使用場景

...
watch:{
  value(val) {
    console.log(val);
    this.visible = val;
  }
}
...

•2、如果要一開始就執(zhí)行

...
watch: {
  firstName: {
    handler(newName, oldName) {
      this.fullName = newName + '-' + this.lastName;
    },
    immediate: true,
  }
}
...

•3、深度監(jiān)聽(數(shù)組、對象)

...
watch: {
  obj: {
    handler(newName, oldName) {
    console.log('///')
  },
  immediate: true,
  deep: true,
}
...

二、關(guān)于子組件修改父組件屬性認識

在vue2.0+ 后不再是雙向綁定,如果要進行雙向綁定需要特殊處理。

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "你修改的屬性名"

•1、通過事件發(fā)送給父組件來修改

**在子組件test1中**
<input type="text" v-model="book"/>
<button @click="add">添加</button>
<p v-for="(item, index) of books" :key="index">{{item}}</p>
...
methods: {
  add() {
    // 直接把數(shù)據(jù)發(fā)送給父組件
    this.$emit('update', this.book);
    this.book = '';
  },
},
**在父組件中**
<test1 :books="books" @update="addBook"></test1>
...
addBook(val) {
  this.books = new Array(val)
},

•2、使用.sync 來讓子組件修改父組件的值(其實是上面方法的精簡版)

**在父組件中,直接在需要傳遞的屬性后面加上.sync**
<test4 :word.sync="word"/>
**在子組件中**
<template>
  <div>
    <h3>{{word}}</h3>
    <input type="text" v-model="str" />
  </div>
</template>
<script>
export default {
  props: {
    word: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      str: '',
    }
  },
  watch: {
    str(newVal, oldVal) {
      // 在監(jiān)聽你使用update事件來更新word,而在父組件不需要調(diào)用該函數(shù)
      this.$emit('update:word', newVal);
    }
  }
}
</script>

•3、在子組件中拷貝一份副本

**子組件中**
export default {
  props: {
    // 已經(jīng)選中的
    checkModalGroup: {
      type: Array,
      default: [],
      required: false,
    }
  },
  data() {
    return{
      copyCheckModalGroup: this.checkModalGroup, // 選中的
    }
  },
  methods: {
    // 一個一個的選擇
    checkAllGroupChange(data) {
      // 把當前的發(fā)送給父組件
      this.$emit('updata', data);
    },
  },
  watch: {
    checkModalGroup(newVal, oldVal) {
      this.copyCheckModalGroup = newVal;
    }
  }
}
**父組件中直接更新傳遞給子組件的數(shù)據(jù)就可以**
...
// 更新子組件數(shù)據(jù)
roleCheckUpdata(data) {
  this.roleGroup = data;
},
...

總結(jié)

以上所述是小編給大家介紹的vue中如何讓子組件修改父組件數(shù)據(jù),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論