国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue .sync修飾符的使用詳解

2024-05-06 15:33:24
字體:
來源:轉載
供稿:網友

vue的官網介紹非常不錯,先通讀一遍。

2.3.0+ 新增

在有些情況下,我們可能需要對一個 prop 進行“雙向綁定”。不幸的是,真正的雙向綁定會帶來維護上的問題,因為子組件可以修改父組件,且在父組件和子組件都沒有明顯的改動來源。

這也是為什么我們推薦以 update:my-prop-name 的模式觸發事件取而代之。舉個例子,在一個包含  title prop 的假設的組件中,我們可以用以下方法表達對其賦新值的意圖:

this.$emit('update:title', newTitle)

然后父組件可以監聽那個事件并根據需要更新一個本地的數據屬性。例如:

<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event"></text-document>

為了方便起見,我們為這種模式提供一個縮寫,即 .sync 修飾符:

<text-document v-bind:title.sync="doc.title"></text-document>

當我們用一個對象同時設置多個 prop 的時候,也可以將這個 .sync 修飾符和  v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

這樣會把 doc 對象中的每一個屬性 (如  title ) 都作為一個獨立的 prop 傳進去,然后各自添加用于更新的  v-on 監聽器。

以下為代碼實例

father.vue

<template> <div class="hello"> //input實時改變wrd的值, 并且會實時改變box里的內容 <input type="text" v-model="wrd"> <box :word.sync="wrd" ></box> </div></template><script>import box from './box' //引入box子組件export default { name: 'HelloWorld', data() { return {  wrd: '' } }, components: { box } }</script>child.vue<template> <div class="hello"> <div class="ipt">  <input type="text" v-model="str"> </div> //word是父元素傳過來的 <h2>{{ word }}</h2> </div></template><script>export default { name: 'box', data() { return {  str: '', } }, props: { word: '' }, watch: { str: function(newValue, oldValue) {  //每當str的值改變則發送事件update:word , 并且把值傳過去  this.$emit('update:word', newValue) } }}</script>

那這個修飾符的原理是什么呢?其實還是vue父組件可以監聽子組件的事件,自組件可以觸發父組件的事件

father.vue

<template> <div class="hello"> <input type="text" v-model="wrd"> <box @incre="boxIncremend" ></box> </div></template><script>import box from './box'export default { name: 'HelloWorld', data() { return {  wrd: '' } }, methods: { boxIncremend(e) {  this.wrd = this.wrd + e } }, components: { box }}</script>child.vue<template> <div class="hello">  <input type="text" v-model="str"> <h2>{{ word }}</h2> </div></template><script>export default { name: 'box', data() { return {  num: 0 } }, props: { word: '' }, watch: { str: function(neww, old) {  //往父級發射incre事件  this.$emit('incre', ++this.num) } },}</script>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 霍州市| 大新县| 无极县| 横山县| 台江县| 威远县| 合山市| 广德县| 淳化县| 嘉祥县| 南城县| 新晃| 肥西县| 怀集县| 会同县| 榆林市| 武鸣县| 宜宾市| 定结县| 嘉兴市| 山东| 广宗县| 栾川县| 泰宁县| 师宗县| 冷水江市| 连云港市| 藁城市| 宿州市| 三亚市| 水城县| 革吉县| 平泉县| 三门县| 中阳县| 女性| 苏尼特右旗| 新化县| 同仁县| 景德镇市| 塘沽区|