本文介紹了vue v-model進行數據綁定,分享給大家,具體如下
官方例子https://vuefe.cn/v2/api/#model
有這么一句話: 默認情況下,一個組件上的 v-model 會把 value 用作 prop 且把 input 用作 event。
示例:
先來一個組件,不用vue-model,正常父子通信
<!-- parent --><template><p class="parent"> <p>我是父親, 對兒子說: {{sthGiveChild}}</p> <Child @returnBack="turnBack" :give="sthGiveChild"></Child></p></template><script>import Child from './Child.vue';export default { data() { return { sthGiveChild: '給你100塊' }; }, components: { Child }, methods: { turnBack(val) { this.sthGiveChild = val; } }}</script><!-- child --><template><p class="child"> <p>我是兒子,父親對我說: {{give}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回應</a></p></template><script>export default { props: { give: String }, methods: { returnBackFn() { this.$emit('returnBack', '還你200塊'); } }}</script>點擊回應后,父親對兒子說的話變成了兒子的回應。兒子收到的信息也變了,實現通信。
改用v-model
<!-- parent --><template><p class="parent"> <p>我是父親, 對兒子說: {{sthGiveChild}}</p> <Child v-model="sthGiveChild"></Child></p></template><script>import Child from './Child.vue';export default { data() { return { sthGiveChild: '給你100塊' }; }, components: { Child }}</script><!-- child --><template><p class="child"> <p>我是兒子,父親對我說: {{give}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回應</a></p></template><script>export default { props: { give: String }, model: { prop: 'give', event: 'returnBack' }, methods: { returnBackFn() { this.$emit('returnBack', '還你200塊'); } }}</script>文案雖有不同,但是效果最終是一致的。
看看官方自定義組件的v-model
官方例子https://vuefe.cn/v2/api/#model
有這么一句話: 默認情況下,一個組件上的 v-model 會把 value 用作 prop 且把 input 用作 event。
嘗試把上邊子組件的例子改一下,也是跑的通的
<!-- child --><template><p class="child"> <p>我是兒子,父親對我說: {{value}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回應</a></p></template><script>export default { props: { value: String }, methods: { returnBackFn() { this.$emit('input', '還你200塊'); } }}</script>
新聞熱點
疑難解答
圖片精選