在父組件中引用的子組件標(biāo)簽上添加屬性屉佳,來渲染可以擁有不同數(shù)據(jù)的子組件谷朝。但是vue 的組件有個特點,如果我們這一次和上一次傳過去的屬性值一樣的話武花,watch 監(jiān)聽的屬性因為沒有新的變化(這次的值和上一次的值一樣watch 中調(diào)用的函數(shù)不執(zhí)行)圆凰,導(dǎo)致對應(yīng)的數(shù)據(jù)也沒有變化。created() 生命周期函數(shù)也是只執(zhí)行一次体箕。但是有時候我們需要這個組件每次都重新生成dom 元素专钉,每次都執(zhí)行created() 函數(shù)。這時候就用到了vue中的key 屬性累铅。
<template>
<div>
<div>
<h1>父級</h1>
<button @click="handleLoad">點擊重新加載子級</button>
</div>
<children :key="timer"></children>
</div>
</template>
<script>
import children from '@/components/parent/children'
export default {
name: 'parent',
components: { children },
data () {
return {
timer: ''
}
},
methods: {
handleLoad () {
this.timer = new Date().getTime()
}
}
}
</script>