Home >Web Front-end >JS Tutorial >How to implement two-way binding between Vue2 parent component and child component

How to implement two-way binding between Vue2 parent component and child component

php中世界最好的语言
php中世界最好的语言Original
2018-04-11 17:30:041467browse

This time I will show you how to implement the two-way binding of the Vue2 parent component and the child component. What are the precautions ? The following is a practical case. Let’s take a look.

Recently I was studying how to write a set of UI components based on Vue2. To achieve two-way binding, I thought about using Vuex, but after observing other excellent UIframework, I found that using Vuex would cause trouble to other users, so I decided to find a solution and consulted several articles. After many articles, I finally found it.

I post the solution here, hoping to help colleagues like me who are new to the Vue framework.

Code logic of subcomponents

<template> 
 <p class="ne-ipt"> 
  <input type="text" v-model="currentValue"> 
 </p> 
</template> 
 
<style lang="less" scoped> 
 @import "../../assets/styles/form/form.less"; 
</style> 
<script> 
 export default { 
  name: 'NeIpt', 
  props: { 
   // 接收一个由父级组件传递过来的值 
   value: { 
    type: String, 
    default: function () { 
     return '' 
    } 
   } 
  }, 
  computed:{ 
   currentValue: { 
    // 动态计算currentValue的值 
    get:function() { 
     return this.value; // 将props中的value赋值给currentValue 
    }, 
    set:function(val) { 
     this.$emit('input', val); // 通过$emit触发父组件 
    } 
   } 
  } 
 } 
</script>

Parent component code logic

<template> 
 <p id="button-index"> 
  <ne-ipt placeholder="姓名" v-model="test"></ne-ipt> 
 </p> 
</template> 
<style> 
</style> 
<script> 
 import NeIpt from './NeIpt' 
 export default { 
  name: 'form-index', 
  data () { 
   return { 
    test: '' 
   } 
  }, 
  components: { 
   NeIpt 
  } 
 } 
</script>

When modifying the currentValue of the subcomponent, the input event is actually triggered through $emit and the value is passed to the caller's v-model, thereby achieving two-way binding.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement the file download function in Django

How to reference local static images in vue

The above is the detailed content of How to implement two-way binding between Vue2 parent component and child component. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn