天天看點

vue重點知識

$nextTick()

1. 使用原由

由于Vue的資料驅動視圖的更新是異步的,也就是在修改資料的當下視圖不會立即更新,而是等同一事件循環中所有資料變化完成之後,統一進行視圖更新。

2. 使用場景

需要在視圖更新之後,基于新的視圖進行操作,一般寫在created和mounted裡面

mounted(){
  this.$nextTick(()=> {
       this.setCircleHeiht()
   })
   window.addEventListener("resize",this.setCircleHeiht)
},
methods:{
    //設定圓的高度
    setCircleHeiht(){
        this.largeHeight = this.$refs.largeCircle[0].offsetWidth
        this.minHeight = this.$refs.minCircle[0].offsetWidth
    }
 }
           

子父元件之間的通信

1. 子元件向父元件傳值

主要是通過$emit()進行傳遞

子元件代碼:

<template>
  <div>
      <h3>這裡是childA</h3>
      <button @click="_send">給父元件傳個消息</button>
  </div>
</template>

<script>
export default {
name:'ChildA',
// 方法集合
methods: {
    _send(){
        this.$emit('send',{nickName:'Lucky'});  //将需要傳的值作為$emit的第二個參數進行傳遞
    }
}
}
</script>
           

父元件代碼:

<ChildA @send="touchMe"></ChildA>
    <h3>子元件的名字:{{getByChildA}}</h3>

<script>
import ChildA from './ChildA'
export default {
  name: 'HelloWorld',
  data () {
    return {
      getByChildA:'',
      name:'',
      age:'',
      msg:''
    }
  },
  components:{
    ChildA,   //父元件中注冊子元件
  },
  methods:{
    touchMe(obj){
      this.getByChildA=obj.nickName;  //将從子元件中擷取的值指派給變量
    }
  }
}
</script>
           

2. 父元件向子元件傳值

方式一:在子元件中使用props進行接收父元件傳過來的值

子元件代碼:

<div>
      <h3>這裡是childC</h3>
      <h3>父元件傳過來的值:姓名:{{inputName}} 年齡:{{inputage}}</h3>
  </div>

<script>
// 這裡可以導入其他檔案(比如:元件,工具js,第三方插件js,json檔案,圖檔檔案等等)

export default {
    //接受父元件傳過來的值
    props:{
        inputName:String,   //定義傳值類型
        inputage:Number
    }
}
</script>
           

注意:props就是一個屬性,不能寫在data裡面

父元件代碼:

<!-- 子元件與父元件之間的契合點 -->
    <ChildC :inputName="name" :inputage="age"></ChildC>
data () {
    return {
      name:'cc',   //父元件要向子元件傳遞的值
      age:20
    }
  },
           

方式二:用this.$refs進行傳遞,在父元件中引入子元件的時候還需要用ref進行綁定

子元件代碼:

<template>
  <div>
      <h3>這裡是childB</h3>
      <h3>父元件傳過來的值:姓名:{{name}} 年齡:{{age}}</h3>
  </div>
</template>

<script>
// 這裡可以導入其他檔案(比如:元件,工具js,第三方插件js,json檔案,圖檔檔案等等)

export default {
  components: {
    
  },
  // 定義屬性
  data() {
    return {
        name:'',
        age:''
    }
  },
  methods: {
      //父元件觸發子元件的init方法
    init(name,age){
        this.name=name;
        this.age=age;
    }
  }
}
</script>
           

父元件代碼:

<button @click="getData">父元件給子元件傳值</button>
    <ChildB ref="myChildB"></ChildB>
methods:{
    getData(){
      //觸發子元件的方法并且傳參   init函數名與子元件中的函數名一緻
      this.$refs.myChildB.init("childB","18")
    }
  }
           

運作結果:

初始時:

vue重點知識

點選按鈕之後:

vue重點知識